forked from hashicorp/go-tfe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
458 lines (385 loc) · 15.8 KB
/
run.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package tfe
import (
"context"
"fmt"
"net/url"
"time"
)
// Compile-time proof of interface implementation.
var _ Runs = (*runs)(nil)
// Runs describes all the run related methods that the Terraform Enterprise
// API supports.
//
// TFE API docs: https://www.terraform.io/docs/cloud/api/run.html
type Runs interface {
// List all the runs of the given workspace.
List(ctx context.Context, workspaceID string, options *RunListOptions) (*RunList, error)
// Create a new run with the given options.
Create(ctx context.Context, options RunCreateOptions) (*Run, error)
// Read a run by its ID.
Read(ctx context.Context, runID string) (*Run, error)
// ReadWithOptions reads a run by its ID using the options supplied
ReadWithOptions(ctx context.Context, runID string, options *RunReadOptions) (*Run, error)
// Apply a run by its ID.
Apply(ctx context.Context, runID string, options RunApplyOptions) error
// Cancel a run by its ID.
Cancel(ctx context.Context, runID string, options RunCancelOptions) error
// Force-cancel a run by its ID.
ForceCancel(ctx context.Context, runID string, options RunForceCancelOptions) error
// Discard a run by its ID.
Discard(ctx context.Context, runID string, options RunDiscardOptions) error
}
// runs implements Runs.
type runs struct {
client *Client
}
// RunStatus represents a run state.
type RunStatus string
// List all available run statuses.
const (
RunApplied RunStatus = "applied"
RunApplyQueued RunStatus = "apply_queued"
RunApplying RunStatus = "applying"
RunCanceled RunStatus = "canceled"
RunConfirmed RunStatus = "confirmed"
RunCostEstimated RunStatus = "cost_estimated"
RunCostEstimating RunStatus = "cost_estimating"
RunDiscarded RunStatus = "discarded"
RunErrored RunStatus = "errored"
RunFetching RunStatus = "fetching"
RunPending RunStatus = "pending"
RunPlanQueued RunStatus = "plan_queued"
RunPlanned RunStatus = "planned"
RunPlannedAndFinished RunStatus = "planned_and_finished"
RunPlanning RunStatus = "planning"
RunPolicyChecked RunStatus = "policy_checked"
RunPolicyChecking RunStatus = "policy_checking"
RunPolicyOverride RunStatus = "policy_override"
RunPolicySoftFailed RunStatus = "policy_soft_failed"
RunPostPlanRunning RunStatus = "post_plan_running"
RunPostPlanCompleted RunStatus = "post_plan_completed"
)
// RunSource represents a source type of a run.
type RunSource string
// List all available run sources.
const (
RunSourceAPI RunSource = "tfe-api"
RunSourceConfigurationVersion RunSource = "tfe-configuration-version"
RunSourceUI RunSource = "tfe-ui"
)
// RunList represents a list of runs.
type RunList struct {
*Pagination
Items []*Run
}
// Run represents a Terraform Enterprise run.
type Run struct {
ID string `jsonapi:"primary,runs"`
Actions *RunActions `jsonapi:"attr,actions"`
AutoApply bool `jsonapi:"attr,auto-apply,omitempty"`
CreatedAt time.Time `jsonapi:"attr,created-at,iso8601"`
ForceCancelAvailableAt time.Time `jsonapi:"attr,force-cancel-available-at,iso8601"`
HasChanges bool `jsonapi:"attr,has-changes"`
IsDestroy bool `jsonapi:"attr,is-destroy"`
Message string `jsonapi:"attr,message"`
Permissions *RunPermissions `jsonapi:"attr,permissions"`
PositionInQueue int `jsonapi:"attr,position-in-queue"`
Refresh bool `jsonapi:"attr,refresh"`
RefreshOnly bool `jsonapi:"attr,refresh-only"`
ReplaceAddrs []string `jsonapi:"attr,replace-addrs,omitempty"`
Source RunSource `jsonapi:"attr,source"`
Status RunStatus `jsonapi:"attr,status"`
StatusTimestamps *RunStatusTimestamps `jsonapi:"attr,status-timestamps"`
TargetAddrs []string `jsonapi:"attr,target-addrs,omitempty"`
Variables []*RunVariable `jsonapi:"attr,variables"`
// Relations
Apply *Apply `jsonapi:"relation,apply"`
ConfigurationVersion *ConfigurationVersion `jsonapi:"relation,configuration-version"`
CostEstimate *CostEstimate `jsonapi:"relation,cost-estimate"`
CreatedBy *User `jsonapi:"relation,created-by"`
Plan *Plan `jsonapi:"relation,plan"`
PolicyChecks []*PolicyCheck `jsonapi:"relation,policy-checks"`
TaskStages []*TaskStage `jsonapi:"relation,task-stages,omitempty"`
Workspace *Workspace `jsonapi:"relation,workspace"`
Comments []*Comment `jsonapi:"relation,comments"`
}
// RunActions represents the run actions.
type RunActions struct {
IsCancelable bool `jsonapi:"attr,is-cancelable"`
IsConfirmable bool `jsonapi:"attr,is-confirmable"`
IsDiscardable bool `jsonapi:"attr,is-discardable"`
IsForceCancelable bool `jsonapi:"attr,is-force-cancelable"`
}
// RunPermissions represents the run permissions.
type RunPermissions struct {
CanApply bool `jsonapi:"attr,can-apply"`
CanCancel bool `jsonapi:"attr,can-cancel"`
CanDiscard bool `jsonapi:"attr,can-discard"`
CanForceCancel bool `jsonapi:"attr,can-force-cancel"`
CanForceExecute bool `jsonapi:"attr,can-force-execute"`
}
// RunStatusTimestamps holds the timestamps for individual run statuses.
type RunStatusTimestamps struct {
AppliedAt time.Time `jsonapi:"attr,applied-at,rfc3339"`
ApplyQueuedAt time.Time `jsonapi:"attr,apply-queued-at,rfc3339"`
ApplyingAt time.Time `jsonapi:"attr,applying-at,rfc3339"`
CanceledAt time.Time `jsonapi:"attr,canceled-at,rfc3339"`
ConfirmedAt time.Time `jsonapi:"attr,confirmed-at,rfc3339"`
CostEstimatedAt time.Time `jsonapi:"attr,cost-estimated-at,rfc3339"`
CostEstimatingAt time.Time `jsonapi:"attr,cost-estimating-at,rfc3339"`
DiscardedAt time.Time `jsonapi:"attr,discarded-at,rfc3339"`
ErroredAt time.Time `jsonapi:"attr,errored-at,rfc3339"`
FetchedAt time.Time `jsonapi:"attr,fetched-at,rfc3339"`
FetchingAt time.Time `jsonapi:"attr,fetching-at,rfc3339"`
ForceCanceledAt time.Time `jsonapi:"attr,force-canceled-at,rfc3339"`
PlanQueueableAt time.Time `jsonapi:"attr,plan-queueable-at,rfc3339"`
PlanQueuedAt time.Time `jsonapi:"attr,plan-queued-at,rfc3339"`
PlannedAndFinishedAt time.Time `jsonapi:"attr,planned-and-finished-at,rfc3339"`
PlannedAt time.Time `jsonapi:"attr,planned-at,rfc3339"`
PlanningAt time.Time `jsonapi:"attr,planning-at,rfc3339"`
PolicyCheckedAt time.Time `jsonapi:"attr,policy-checked-at,rfc3339"`
PolicySoftFailedAt time.Time `jsonapi:"attr,policy-soft-failed-at,rfc3339"`
}
// RunIncludeOpt represents the available options for include query params.
// https://www.terraform.io/docs/cloud/api/run.html#available-related-resources
type RunIncludeOpt string
const (
RunPlan RunIncludeOpt = "plan"
RunApply RunIncludeOpt = "apply"
RunCreatedBy RunIncludeOpt = "created_by"
RunCostEstimate RunIncludeOpt = "cost_estimate"
RunConfigVer RunIncludeOpt = "configuration_version"
RunConfigVerIngress RunIncludeOpt = "configuration_version.ingress_attributes"
RunWorkspace RunIncludeOpt = "workspace"
RunTaskStages RunIncludeOpt = "task_stages"
)
// RunListOptions represents the options for listing runs.
type RunListOptions struct {
ListOptions
// Optional: A list of relations to include. See available resources:
// https://www.terraform.io/docs/cloud/api/run.html#available-related-resources
Include []RunIncludeOpt `url:"include,omitempty"`
}
// RunReadOptions represents the options for reading a run.
type RunReadOptions struct {
// Optional: A list of relations to include. See available resources:
// https://www.terraform.io/docs/cloud/api/run.html#available-related-resources
Include []RunIncludeOpt `url:"include,omitempty"`
}
// RunCreateOptions represents the options for creating a new run.
type RunCreateOptions struct {
// Type is a public field utilized by JSON:API to
// set the resource type via the field tag.
// It is not a user-defined value and does not need to be set.
// https://jsonapi.org/format/#crud-creating
Type string `jsonapi:"primary,runs"`
// Specifies if this plan is a destroy plan, which will destroy all
// provisioned resources.
IsDestroy *bool `jsonapi:"attr,is-destroy,omitempty"`
// Refresh determines if the run should
// update the state prior to checking for differences
Refresh *bool `jsonapi:"attr,refresh,omitempty"`
// RefreshOnly determines whether the run should ignore config changes
// and refresh the state only
RefreshOnly *bool `jsonapi:"attr,refresh-only,omitempty"`
// Specifies the message to be associated with this run.
Message *string `jsonapi:"attr,message,omitempty"`
// Specifies the configuration version to use for this run. If the
// configuration version object is omitted, the run will be created using the
// workspace's latest configuration version.
ConfigurationVersion *ConfigurationVersion `jsonapi:"relation,configuration-version"`
// Specifies the workspace where the run will be executed.
Workspace *Workspace `jsonapi:"relation,workspace"`
// If non-empty, requests that Terraform should create a plan including
// actions only for the given objects (specified using resource address
// syntax) and the objects they depend on.
//
// This capability is provided for exceptional circumstances only, such as
// recovering from mistakes or working around existing Terraform
// limitations. Terraform will generally mention the -target command line
// option in its error messages describing situations where setting this
// argument may be appropriate. This argument should not be used as part
// of routine workflow and Terraform will emit warnings reminding about
// this whenever this property is set.
TargetAddrs []string `jsonapi:"attr,target-addrs,omitempty"`
// If non-empty, requests that Terraform create a plan that replaces
// (destroys and then re-creates) the objects specified by the given
// resource addresses.
ReplaceAddrs []string `jsonapi:"attr,replace-addrs,omitempty"`
// AutoApply determines if the run should be applied automatically without
// user confirmation. It defaults to the Workspace.AutoApply setting.
AutoApply *bool `jsonapi:"attr,auto-apply,omitempty"`
// RunVariables allows you to specify terraform input variables for
// a particular run, prioritized over variables defined on the workspace.
Variables []*RunVariable `jsonapi:"attr,variables,omitempty"`
}
// RunApplyOptions represents the options for applying a run.
type RunApplyOptions struct {
// An optional comment about the run.
Comment *string `json:"comment,omitempty"`
}
// RunCancelOptions represents the options for canceling a run.
type RunCancelOptions struct {
// An optional explanation for why the run was canceled.
Comment *string `json:"comment,omitempty"`
}
// RunVariable represents a variable that can be applied to a run. All values must be expressed as an HCL literal
// in the same syntax you would use when writing terraform code. See https://www.terraform.io/docs/language/expressions/types.html#types
// for more details.
type RunVariable struct {
Key string `jsonapi:"attr,key"`
Value string `jsonapi:"attr,value"`
}
// RunForceCancelOptions represents the options for force-canceling a run.
type RunForceCancelOptions struct {
// An optional comment explaining the reason for the force-cancel.
Comment *string `json:"comment,omitempty"`
}
// RunDiscardOptions represents the options for discarding a run.
type RunDiscardOptions struct {
// An optional explanation for why the run was discarded.
Comment *string `json:"comment,omitempty"`
}
// List all the runs of the given workspace.
func (s *runs) List(ctx context.Context, workspaceID string, options *RunListOptions) (*RunList, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf("workspaces/%s/runs", url.QueryEscape(workspaceID))
req, err := s.client.newRequest("GET", u, options)
if err != nil {
return nil, err
}
rl := &RunList{}
err = s.client.do(ctx, req, rl)
if err != nil {
return nil, err
}
return rl, nil
}
// Create a new run with the given options.
func (s *runs) Create(ctx context.Context, options RunCreateOptions) (*Run, error) {
if err := options.valid(); err != nil {
return nil, err
}
req, err := s.client.newRequest("POST", "runs", &options)
if err != nil {
return nil, err
}
r := &Run{}
err = s.client.do(ctx, req, r)
if err != nil {
return nil, err
}
return r, nil
}
// Read a run by its ID.
func (s *runs) Read(ctx context.Context, runID string) (*Run, error) {
return s.ReadWithOptions(ctx, runID, nil)
}
// Read a run by its ID with the given options.
func (s *runs) ReadWithOptions(ctx context.Context, runID string, options *RunReadOptions) (*Run, error) {
if !validStringID(&runID) {
return nil, ErrInvalidRunID
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf("runs/%s", url.QueryEscape(runID))
req, err := s.client.newRequest("GET", u, options)
if err != nil {
return nil, err
}
r := &Run{}
err = s.client.do(ctx, req, r)
if err != nil {
return nil, err
}
return r, nil
}
// Apply a run by its ID.
func (s *runs) Apply(ctx context.Context, runID string, options RunApplyOptions) error {
if !validStringID(&runID) {
return ErrInvalidRunID
}
u := fmt.Sprintf("runs/%s/actions/apply", url.QueryEscape(runID))
req, err := s.client.newRequest("POST", u, &options)
if err != nil {
return err
}
return s.client.do(ctx, req, nil)
}
// Cancel a run by its ID.
func (s *runs) Cancel(ctx context.Context, runID string, options RunCancelOptions) error {
if !validStringID(&runID) {
return ErrInvalidRunID
}
u := fmt.Sprintf("runs/%s/actions/cancel", url.QueryEscape(runID))
req, err := s.client.newRequest("POST", u, &options)
if err != nil {
return err
}
return s.client.do(ctx, req, nil)
}
// ForceCancel is used to forcefully cancel a run by its ID.
func (s *runs) ForceCancel(ctx context.Context, runID string, options RunForceCancelOptions) error {
if !validStringID(&runID) {
return ErrInvalidRunID
}
u := fmt.Sprintf("runs/%s/actions/force-cancel", url.QueryEscape(runID))
req, err := s.client.newRequest("POST", u, &options)
if err != nil {
return err
}
return s.client.do(ctx, req, nil)
}
// Discard a run by its ID.
func (s *runs) Discard(ctx context.Context, runID string, options RunDiscardOptions) error {
if !validStringID(&runID) {
return ErrInvalidRunID
}
u := fmt.Sprintf("runs/%s/actions/discard", url.QueryEscape(runID))
req, err := s.client.newRequest("POST", u, &options)
if err != nil {
return err
}
return s.client.do(ctx, req, nil)
}
func (o RunCreateOptions) valid() error {
if o.Workspace == nil {
return ErrRequiredWorkspace
}
return nil
}
func (o *RunReadOptions) valid() error {
if o == nil {
return nil // nothing to validate
}
if err := validateRunIncludeParam(o.Include); err != nil {
return err
}
return nil
}
func (o *RunListOptions) valid() error {
if o == nil {
return nil // nothing to validate
}
if err := validateRunIncludeParam(o.Include); err != nil {
return err
}
return nil
}
func validateRunIncludeParam(params []RunIncludeOpt) error {
for _, p := range params {
switch p {
case RunPlan, RunApply, RunCreatedBy, RunCostEstimate, RunConfigVer, RunConfigVerIngress, RunWorkspace, RunTaskStages:
// do nothing
default:
return ErrInvalidIncludeValue
}
}
return nil
}