This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
tfe.go
559 lines (503 loc) · 16.7 KB
/
tfe.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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
package workspace
import (
"context"
"errors"
"fmt"
"net/http"
"reflect"
"github.com/gorilla/mux"
"github.com/leg100/otf/internal"
"github.com/leg100/otf/internal/http/decode"
"github.com/leg100/otf/internal/rbac"
"github.com/leg100/otf/internal/resource"
"github.com/leg100/otf/internal/tfeapi"
"github.com/leg100/otf/internal/tfeapi/types"
)
type (
// byWorkspaceName are parameters used when looking up a workspace by
// name
byWorkspaceName struct {
Name string `schema:"workspace_name,required"`
Organization string `schema:"organization_name,required"`
}
// tfe implements the TFC/E workspaces API:
//
// https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces
tfe struct {
*Service
*tfeapi.Responder
}
)
func (a *tfe) addHandlers(r *mux.Router) {
r = r.PathPrefix(tfeapi.APIPrefixV2).Subrouter()
r.HandleFunc("/organizations/{organization_name}/workspaces", a.listWorkspaces).Methods("GET")
r.HandleFunc("/organizations/{organization_name}/workspaces", a.createWorkspace).Methods("POST")
r.HandleFunc("/organizations/{organization_name}/workspaces/{workspace_name}", a.getWorkspaceByName).Methods("GET")
r.HandleFunc("/organizations/{organization_name}/workspaces/{workspace_name}", a.updateWorkspaceByName).Methods("PATCH")
r.HandleFunc("/organizations/{organization_name}/workspaces/{workspace_name}", a.deleteWorkspaceByName).Methods("DELETE")
r.HandleFunc("/workspaces/{workspace_id}", a.updateWorkspaceByID).Methods("PATCH")
r.HandleFunc("/workspaces/{workspace_id}", a.getWorkspace).Methods("GET")
r.HandleFunc("/workspaces/{workspace_id}", a.deleteWorkspace).Methods("DELETE")
r.HandleFunc("/workspaces/{workspace_id}/actions/lock", a.lockWorkspace).Methods("POST")
r.HandleFunc("/workspaces/{workspace_id}/actions/unlock", a.unlockWorkspace).Methods("POST")
r.HandleFunc("/workspaces/{workspace_id}/actions/force-unlock", a.forceUnlockWorkspace).Methods("POST")
}
func (a *tfe) createWorkspace(w http.ResponseWriter, r *http.Request) {
var params types.WorkspaceCreateOptions
if err := decode.Route(¶ms, r); err != nil {
tfeapi.Error(w, err)
return
}
if err := tfeapi.Unmarshal(r.Body, ¶ms); err != nil {
tfeapi.Error(w, err)
return
}
opts := CreateOptions{
AgentPoolID: params.AgentPoolID,
AllowDestroyPlan: params.AllowDestroyPlan,
AutoApply: params.AutoApply,
Description: params.Description,
ExecutionMode: (*ExecutionMode)(params.ExecutionMode),
GlobalRemoteState: params.GlobalRemoteState,
MigrationEnvironment: params.MigrationEnvironment,
Name: params.Name,
Organization: params.Organization,
QueueAllRuns: params.QueueAllRuns,
SpeculativeEnabled: params.SpeculativeEnabled,
SourceName: params.SourceName,
SourceURL: params.SourceURL,
StructuredRunOutputEnabled: params.StructuredRunOutputEnabled,
TerraformVersion: params.TerraformVersion,
TriggerPrefixes: params.TriggerPrefixes,
TriggerPatterns: params.TriggerPatterns,
WorkingDirectory: params.WorkingDirectory,
// convert from json:api structs to tag specs
Tags: toTagSpecs(params.Tags),
}
// Always trigger runs if neither trigger patterns nor tags regex are set
if len(params.TriggerPatterns) == 0 && (params.VCSRepo == nil || params.VCSRepo.TagsRegex == nil) {
opts.AlwaysTrigger = internal.Bool(true)
}
if params.Operations != nil {
if params.ExecutionMode != nil {
err := errors.New("operations is deprecated and cannot be specified when execution mode is used")
tfeapi.Error(w, err)
return
}
if *params.Operations {
opts.ExecutionMode = ExecutionModePtr(RemoteExecutionMode)
} else {
opts.ExecutionMode = ExecutionModePtr(LocalExecutionMode)
}
}
if params.VCSRepo != nil {
if params.VCSRepo.Identifier == nil || params.VCSRepo.OAuthTokenID == nil {
tfeapi.Error(w, errors.New("must specify both oauth-token-id and identifier attributes for vcs-repo"))
return
}
opts.ConnectOptions = &ConnectOptions{
RepoPath: params.VCSRepo.Identifier,
VCSProviderID: params.VCSRepo.OAuthTokenID,
Branch: params.VCSRepo.Branch,
TagsRegex: params.VCSRepo.TagsRegex,
}
}
ws, err := a.Create(r.Context(), opts)
if err != nil {
tfeapi.Error(w, err)
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusCreated)
}
func (a *tfe) getWorkspace(w http.ResponseWriter, r *http.Request) {
id, err := decode.Param("workspace_id", r)
if err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.Get(r.Context(), id)
if err != nil {
tfeapi.Error(w, err)
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusOK)
}
func (a *tfe) getWorkspaceByName(w http.ResponseWriter, r *http.Request) {
var params byWorkspaceName
if err := decode.All(¶ms, r); err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.GetByName(r.Context(), params.Organization, params.Name)
if err != nil {
tfeapi.Error(w, err)
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusOK)
}
func (a *tfe) listWorkspaces(w http.ResponseWriter, r *http.Request) {
organization, err := decode.Param("organization_name", r)
if err != nil {
tfeapi.Error(w, err)
return
}
var params types.WorkspaceListOptions
if err := decode.All(¶ms, r); err != nil {
tfeapi.Error(w, err)
return
}
page, err := a.List(r.Context(), ListOptions{
Search: params.Search,
Organization: &organization,
PageOptions: resource.PageOptions(params.ListOptions),
Tags: internal.SplitCSV(params.Tags),
})
if err != nil {
tfeapi.Error(w, err)
return
}
// convert items
items := make([]*types.Workspace, len(page.Items))
for i, from := range page.Items {
to, err := a.convert(from, r)
if err != nil {
tfeapi.Error(w, err)
return
}
items[i] = to
}
a.RespondWithPage(w, r, items, page.Pagination)
}
// updateWorkspaceByID updates a workspace using its ID.
//
// TODO: support updating workspace's vcs repo.
func (a *tfe) updateWorkspaceByID(w http.ResponseWriter, r *http.Request) {
workspaceID, err := decode.Param("workspace_id", r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.updateWorkspace(w, r, workspaceID)
}
// updateWorkspaceByName updates a workspace using its name and organization.
//
// TODO: support updating workspace's vcs repo.
func (a *tfe) updateWorkspaceByName(w http.ResponseWriter, r *http.Request) {
var params byWorkspaceName
if err := decode.Route(¶ms, r); err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.GetByName(r.Context(), params.Organization, params.Name)
if err != nil {
tfeapi.Error(w, err)
return
}
a.updateWorkspace(w, r, ws.ID)
}
func (a *tfe) lockWorkspace(w http.ResponseWriter, r *http.Request) {
id, err := decode.Param("workspace_id", r)
if err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.Lock(r.Context(), id, nil)
if err != nil {
if errors.Is(err, ErrWorkspaceAlreadyLocked) {
http.Error(w, "", http.StatusConflict)
} else {
tfeapi.Error(w, err)
}
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusOK)
}
func (a *tfe) unlockWorkspace(w http.ResponseWriter, r *http.Request) {
a.unlock(w, r, false)
}
func (a *tfe) forceUnlockWorkspace(w http.ResponseWriter, r *http.Request) {
a.unlock(w, r, true)
}
func (a *tfe) unlock(w http.ResponseWriter, r *http.Request, force bool) {
id, err := decode.Param("workspace_id", r)
if err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.Unlock(r.Context(), id, nil, force)
if err != nil {
if errors.Is(err, ErrWorkspaceAlreadyUnlocked) || errors.Is(err, ErrWorkspaceLockedByRun) {
tfeapi.Error(w, &internal.HTTPError{
Code: http.StatusConflict,
Message: err.Error(),
})
} else {
tfeapi.Error(w, err)
}
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusOK)
}
func (a *tfe) deleteWorkspace(w http.ResponseWriter, r *http.Request) {
workspaceID, err := decode.Param("workspace_id", r)
if err != nil {
tfeapi.Error(w, err)
return
}
_, err = a.Delete(r.Context(), workspaceID)
if err != nil {
tfeapi.Error(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *tfe) deleteWorkspaceByName(w http.ResponseWriter, r *http.Request) {
var params byWorkspaceName
if err := decode.All(¶ms, r); err != nil {
tfeapi.Error(w, err)
return
}
ws, err := a.GetByName(r.Context(), params.Organization, params.Name)
if err != nil {
tfeapi.Error(w, err)
return
}
_, err = a.Delete(r.Context(), ws.ID)
if err != nil {
tfeapi.Error(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *tfe) updateWorkspace(w http.ResponseWriter, r *http.Request, workspaceID string) {
params := types.WorkspaceUpdateOptions{}
if err := tfeapi.Unmarshal(r.Body, ¶ms); err != nil {
tfeapi.Error(w, err)
return
}
if err := params.Validate(); err != nil {
tfeapi.Error(w, err)
return
}
opts := UpdateOptions{
AgentPoolID: params.AgentPoolID,
AllowDestroyPlan: params.AllowDestroyPlan,
AutoApply: params.AutoApply,
Description: params.Description,
ExecutionMode: (*ExecutionMode)(params.ExecutionMode),
GlobalRemoteState: params.GlobalRemoteState,
Name: params.Name,
QueueAllRuns: params.QueueAllRuns,
SpeculativeEnabled: params.SpeculativeEnabled,
StructuredRunOutputEnabled: params.StructuredRunOutputEnabled,
TerraformVersion: params.TerraformVersion,
TriggerPrefixes: params.TriggerPrefixes,
TriggerPatterns: params.TriggerPatterns,
WorkingDirectory: params.WorkingDirectory,
}
// If file-triggers-enabled is set to false and tags regex is unspecified
// then enable always trigger runs for this workspace.
//
// TODO: return error when client has sent incompatible combinations of
// options:
// (a) file-triggers-enabled=true and tags-regex=non-nil
// (b) file-triggers-enabled=true and trigger-prefixes=empty
// (b) trigger-prefixes=non-empty and tags-regex=non-nil
if (params.FileTriggersEnabled != nil && !*params.FileTriggersEnabled) && (!params.VCSRepo.Set || !params.VCSRepo.Valid || params.VCSRepo.TagsRegex == nil) {
opts.AlwaysTrigger = internal.Bool(true)
}
if params.VCSRepo.Set {
if params.VCSRepo.Valid {
// client has provided non-null vcs options, which means they either
// want to connect the workspace or modify the connection.
opts.ConnectOptions = &ConnectOptions{
RepoPath: params.VCSRepo.Identifier,
VCSProviderID: params.VCSRepo.OAuthTokenID,
Branch: params.VCSRepo.Branch,
TagsRegex: params.VCSRepo.TagsRegex,
}
} else {
// client has explicitly set VCS options to null, which means they
// want the workspace to be disconnected.
opts.Disconnect = true
}
}
ws, err := a.Update(r.Context(), workspaceID, opts)
if err != nil {
tfeapi.Error(w, err)
return
}
converted, err := a.convert(ws, r)
if err != nil {
tfeapi.Error(w, err)
return
}
a.Respond(w, r, converted, http.StatusOK)
}
func (a *tfe) convert(from *Workspace, r *http.Request) (*types.Workspace, error) {
subject, err := internal.SubjectFromContext(r.Context())
if err != nil {
return nil, err
}
policy, err := a.GetPolicy(r.Context(), from.ID)
if err != nil {
return nil, err
}
perms := &types.WorkspacePermissions{
CanLock: subject.CanAccessWorkspace(rbac.LockWorkspaceAction, policy),
CanUnlock: subject.CanAccessWorkspace(rbac.UnlockWorkspaceAction, policy),
CanForceUnlock: subject.CanAccessWorkspace(rbac.UnlockWorkspaceAction, policy),
CanQueueApply: subject.CanAccessWorkspace(rbac.ApplyRunAction, policy),
CanQueueDestroy: subject.CanAccessWorkspace(rbac.ApplyRunAction, policy),
CanQueueRun: subject.CanAccessWorkspace(rbac.CreateRunAction, policy),
CanDestroy: subject.CanAccessWorkspace(rbac.DeleteWorkspaceAction, policy),
CanReadSettings: subject.CanAccessWorkspace(rbac.GetWorkspaceAction, policy),
CanUpdate: subject.CanAccessWorkspace(rbac.UpdateWorkspaceAction, policy),
CanUpdateVariable: subject.CanAccessWorkspace(rbac.UpdateWorkspaceAction, policy),
}
to := &types.Workspace{
ID: from.ID,
Actions: &types.WorkspaceActions{
IsDestroyable: true,
},
AllowDestroyPlan: from.AllowDestroyPlan,
AutoApply: from.AutoApply,
CanQueueDestroyPlan: from.CanQueueDestroyPlan,
CreatedAt: from.CreatedAt,
Description: from.Description,
Environment: from.Environment,
ExecutionMode: string(from.ExecutionMode),
GlobalRemoteState: from.GlobalRemoteState,
Locked: from.Locked(),
MigrationEnvironment: from.MigrationEnvironment,
Name: from.Name,
// Operations is deprecated but clients and go-tfe tests still use it
Operations: from.ExecutionMode == "remote",
Permissions: perms,
QueueAllRuns: from.QueueAllRuns,
SpeculativeEnabled: from.SpeculativeEnabled,
SourceName: from.SourceName,
SourceURL: from.SourceURL,
StructuredRunOutputEnabled: from.StructuredRunOutputEnabled,
TerraformVersion: from.TerraformVersion,
TriggerPrefixes: from.TriggerPrefixes,
TriggerPatterns: from.TriggerPatterns,
WorkingDirectory: from.WorkingDirectory,
TagNames: from.Tags,
UpdatedAt: from.UpdatedAt,
Organization: &types.Organization{Name: from.Organization},
}
if from.AgentPoolID != nil {
to.AgentPoolID = *from.AgentPoolID
}
if len(from.TriggerPrefixes) > 0 || len(from.TriggerPatterns) > 0 {
to.FileTriggersEnabled = true
}
if from.LatestRun != nil {
to.CurrentRun = &types.Run{ID: from.LatestRun.ID}
}
// Add VCS repo to json:api struct if connected. NOTE: the terraform CLI
// uses the presence of VCS repo to determine whether to allow a terraform
// apply or not, displaying the following message if not:
//
// Apply not allowed for workspaces with a VCS connection
//
// A workspace that is connected to a VCS requires the VCS-driven workflow to ensure that the VCS remains the single source of truth.
//
// OTF permits the user to disable this behaviour by ommiting this info and
// fool the terraform CLI into thinking its not a workspace with a VCS
// connection.
if from.Connection != nil {
if !from.Connection.AllowCLIApply || !tfeapi.IsTerraformCLI(r) {
to.VCSRepo = &types.VCSRepo{
OAuthTokenID: from.Connection.VCSProviderID,
Branch: from.Connection.Branch,
Identifier: from.Connection.Repo,
TagsRegex: from.Connection.TagsRegex,
}
}
}
return to, nil
}
func (a *tfe) include(ctx context.Context, v any) ([]any, error) {
dst := reflect.Indirect(reflect.ValueOf(v))
// v must be a struct with a field named Workspace of type *types.Workspace
if dst.Kind() != reflect.Struct {
return nil, nil
}
field := dst.FieldByName("Workspace")
if !field.IsValid() {
return nil, nil
}
onlyID, ok := field.Interface().(*types.Workspace)
if !ok {
return nil, nil
}
// onlyID only contains the ID field, e.g. types.Workspace{ID:
// "ws-123"}; so now retrieve the fully populated workspace, convert to a
// tfe workspace and return.
ws, err := a.Get(ctx, onlyID.ID)
if err != nil {
return nil, fmt.Errorf("retrieving workspace: %w", err)
}
include, err := a.convert(ws, (&http.Request{}).WithContext(ctx))
if err != nil {
return nil, err
}
return []any{include}, nil
}
func (a *tfe) includeMany(ctx context.Context, v any) ([]any, error) {
dst := reflect.Indirect(reflect.ValueOf(v))
// v must be a struct with a field named Workspaces of type []*types.Workspace
if dst.Kind() != reflect.Struct {
return nil, nil
}
field := dst.FieldByName("Workspaces")
if !field.IsValid() {
return nil, nil
}
onlyIDs, ok := field.Interface().([]*types.Workspace)
if !ok {
return nil, nil
}
// onlyIDs only contains the ID field, e.g. []*types.Workspace{{ID:
// "ws-123"}}; so now retrieve the fully populated workspaces, convert and
// return them.
include := make([]any, len(onlyIDs))
for i, onlyID := range onlyIDs {
ws, err := a.Get(ctx, onlyID.ID)
if err != nil {
return nil, fmt.Errorf("retrieving workspace: %w", err)
}
include[i], err = a.convert(ws, (&http.Request{}).WithContext(ctx))
if err != nil {
return nil, err
}
}
return include, nil
}