forked from hashicorp/go-tfe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkspace.go
1691 lines (1385 loc) · 60.9 KB
/
workspace.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tfe
import (
"context"
"fmt"
"io"
"net/url"
"strings"
"time"
"github.com/hashicorp/jsonapi"
)
// Compile-time proof of interface implementation.
var _ Workspaces = (*workspaces)(nil)
// Workspaces describes all the workspace related methods that the Terraform
// Enterprise API supports.
//
// TFE API docs: https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces
type Workspaces interface {
// List all the workspaces within an organization.
List(ctx context.Context, organization string, options *WorkspaceListOptions) (*WorkspaceList, error)
// Create is used to create a new workspace.
Create(ctx context.Context, organization string, options WorkspaceCreateOptions) (*Workspace, error)
// Read a workspace by its name and organization name.
Read(ctx context.Context, organization string, workspace string) (*Workspace, error)
// ReadWithOptions reads a workspace by name and organization name with given options.
ReadWithOptions(ctx context.Context, organization string, workspace string, options *WorkspaceReadOptions) (*Workspace, error)
// Readme gets the readme of a workspace by its ID.
Readme(ctx context.Context, workspaceID string) (io.Reader, error)
// ReadByID reads a workspace by its ID.
ReadByID(ctx context.Context, workspaceID string) (*Workspace, error)
// ReadByIDWithOptions reads a workspace by its ID with the given options.
ReadByIDWithOptions(ctx context.Context, workspaceID string, options *WorkspaceReadOptions) (*Workspace, error)
// Update settings of an existing workspace.
Update(ctx context.Context, organization string, workspace string, options WorkspaceUpdateOptions) (*Workspace, error)
// UpdateByID updates the settings of an existing workspace.
UpdateByID(ctx context.Context, workspaceID string, options WorkspaceUpdateOptions) (*Workspace, error)
// Delete a workspace by its name.
Delete(ctx context.Context, organization string, workspace string) error
// DeleteByID deletes a workspace by its ID.
DeleteByID(ctx context.Context, workspaceID string) error
// SafeDelete a workspace by its name.
SafeDelete(ctx context.Context, organization string, workspace string) error
// SafeDeleteByID deletes a workspace by its ID.
SafeDeleteByID(ctx context.Context, workspaceID string) error
// RemoveVCSConnection from a workspace.
RemoveVCSConnection(ctx context.Context, organization, workspace string) (*Workspace, error)
// RemoveVCSConnectionByID removes a VCS connection from a workspace.
RemoveVCSConnectionByID(ctx context.Context, workspaceID string) (*Workspace, error)
// Lock a workspace by its ID.
Lock(ctx context.Context, workspaceID string, options WorkspaceLockOptions) (*Workspace, error)
// Unlock a workspace by its ID.
Unlock(ctx context.Context, workspaceID string) (*Workspace, error)
// ForceUnlock a workspace by its ID.
ForceUnlock(ctx context.Context, workspaceID string) (*Workspace, error)
// AssignSSHKey to a workspace.
AssignSSHKey(ctx context.Context, workspaceID string, options WorkspaceAssignSSHKeyOptions) (*Workspace, error)
// UnassignSSHKey from a workspace.
UnassignSSHKey(ctx context.Context, workspaceID string) (*Workspace, error)
// ListRemoteStateConsumers reads the remote state consumers for a workspace.
ListRemoteStateConsumers(ctx context.Context, workspaceID string, options *RemoteStateConsumersListOptions) (*WorkspaceList, error)
// AddRemoteStateConsumers adds remote state consumers to a workspace.
AddRemoteStateConsumers(ctx context.Context, workspaceID string, options WorkspaceAddRemoteStateConsumersOptions) error
// RemoveRemoteStateConsumers removes remote state consumers from a workspace.
RemoveRemoteStateConsumers(ctx context.Context, workspaceID string, options WorkspaceRemoveRemoteStateConsumersOptions) error
// UpdateRemoteStateConsumers updates all the remote state consumers for a workspace
// to match the workspaces in the update options.
UpdateRemoteStateConsumers(ctx context.Context, workspaceID string, options WorkspaceUpdateRemoteStateConsumersOptions) error
// ListTags reads the tags for a workspace.
ListTags(ctx context.Context, workspaceID string, options *WorkspaceTagListOptions) (*TagList, error)
// AddTags appends tags to a workspace
AddTags(ctx context.Context, workspaceID string, options WorkspaceAddTagsOptions) error
// RemoveTags removes tags from a workspace
RemoveTags(ctx context.Context, workspaceID string, options WorkspaceRemoveTagsOptions) error
// ReadDataRetentionPolicy reads a workspace's data retention policy
//
// Deprecated: Use ReadDataRetentionPolicyChoice instead.
// **Note: This functionality is only available in Terraform Enterprise versions v202311-1 and v202312-1.**
ReadDataRetentionPolicy(ctx context.Context, workspaceID string) (*DataRetentionPolicy, error)
// ReadDataRetentionPolicyChoice reads a workspace's data retention policy
// **Note: This functionality is only available in Terraform Enterprise.**
ReadDataRetentionPolicyChoice(ctx context.Context, workspaceID string) (*DataRetentionPolicyChoice, error)
// SetDataRetentionPolicy sets a workspace's data retention policy to delete data older than a certain number of days
//
// Deprecated: Use SetDataRetentionPolicyDeleteOlder instead
// **Note: This functionality is only available in Terraform Enterprise versions v202311-1 and v202312-1.**
SetDataRetentionPolicy(ctx context.Context, workspaceID string, options DataRetentionPolicySetOptions) (*DataRetentionPolicy, error)
// SetDataRetentionPolicyDeleteOlder sets a workspace's data retention policy to delete data older than a certain number of days
// **Note: This functionality is only available in Terraform Enterprise.**
SetDataRetentionPolicyDeleteOlder(ctx context.Context, workspaceID string, options DataRetentionPolicyDeleteOlderSetOptions) (*DataRetentionPolicyDeleteOlder, error)
// SetDataRetentionPolicyDontDelete sets a workspace's data retention policy to explicitly not delete data
// **Note: This functionality is only available in Terraform Enterprise.**
SetDataRetentionPolicyDontDelete(ctx context.Context, workspaceID string, options DataRetentionPolicyDontDeleteSetOptions) (*DataRetentionPolicyDontDelete, error)
// DeleteDataRetentionPolicy deletes a workspace's data retention policy
// **Note: This functionality is only available in Terraform Enterprise.**
DeleteDataRetentionPolicy(ctx context.Context, workspaceID string) error
// ListTagBindings lists all tag bindings associated with the workspace.
ListTagBindings(ctx context.Context, workspaceID string) ([]*TagBinding, error)
// ListEffectiveTagBindings lists all tag bindings associated with the workspace which may be
// either inherited from a project or binded to the workspace itself.
ListEffectiveTagBindings(ctx context.Context, workspaceID string) ([]*EffectiveTagBinding, error)
// AddTagBindings adds or modifies the value of existing tag binding keys for a workspace.
AddTagBindings(ctx context.Context, workspaceID string, options WorkspaceAddTagBindingsOptions) ([]*TagBinding, error)
}
// workspaces implements Workspaces.
type workspaces struct {
client *Client
}
// WorkspaceList represents a list of workspaces.
type WorkspaceList struct {
*Pagination
Items []*Workspace
}
// WorkspaceAddTagBindingsOptions represents the options for adding tag bindings
// to a workspace.
type WorkspaceAddTagBindingsOptions struct {
TagBindings []*TagBinding
}
// LockedByChoice is a choice type struct that represents the possible values
// within a polymorphic relation. If a value is available, exactly one field
// will be non-nil.
type LockedByChoice struct {
Run *Run
User *User
Team *Team
}
// Workspace represents a Terraform Enterprise workspace.
type Workspace struct {
ID string `jsonapi:"primary,workspaces"`
Actions *WorkspaceActions `jsonapi:"attr,actions"`
AllowDestroyPlan bool `jsonapi:"attr,allow-destroy-plan"`
AssessmentsEnabled bool `jsonapi:"attr,assessments-enabled"`
AutoApply bool `jsonapi:"attr,auto-apply"`
AutoApplyRunTrigger bool `jsonapi:"attr,auto-apply-run-trigger"`
AutoDestroyAt jsonapi.NullableAttr[time.Time] `jsonapi:"attr,auto-destroy-at,iso8601,omitempty"`
AutoDestroyActivityDuration jsonapi.NullableAttr[string] `jsonapi:"attr,auto-destroy-activity-duration,omitempty"`
CanQueueDestroyPlan bool `jsonapi:"attr,can-queue-destroy-plan"`
CreatedAt time.Time `jsonapi:"attr,created-at,iso8601"`
Description string `jsonapi:"attr,description"`
Environment string `jsonapi:"attr,environment"`
ExecutionMode string `jsonapi:"attr,execution-mode"`
FileTriggersEnabled bool `jsonapi:"attr,file-triggers-enabled"`
GlobalRemoteState bool `jsonapi:"attr,global-remote-state"`
Locked bool `jsonapi:"attr,locked"`
MigrationEnvironment string `jsonapi:"attr,migration-environment"`
Name string `jsonapi:"attr,name"`
NoCodeUpgradeAvailable bool `jsonapi:"attr,no-code-upgrade-available"`
Operations bool `jsonapi:"attr,operations"`
Permissions *WorkspacePermissions `jsonapi:"attr,permissions"`
QueueAllRuns bool `jsonapi:"attr,queue-all-runs"`
SpeculativeEnabled bool `jsonapi:"attr,speculative-enabled"`
SourceName string `jsonapi:"attr,source-name"`
SourceURL string `jsonapi:"attr,source-url"`
StructuredRunOutputEnabled bool `jsonapi:"attr,structured-run-output-enabled"`
TerraformVersion string `jsonapi:"attr,terraform-version"`
TriggerPrefixes []string `jsonapi:"attr,trigger-prefixes"`
TriggerPatterns []string `jsonapi:"attr,trigger-patterns"`
VCSRepo *VCSRepo `jsonapi:"attr,vcs-repo"`
WorkingDirectory string `jsonapi:"attr,working-directory"`
UpdatedAt time.Time `jsonapi:"attr,updated-at,iso8601"`
ResourceCount int `jsonapi:"attr,resource-count"`
ApplyDurationAverage time.Duration `jsonapi:"attr,apply-duration-average"`
PlanDurationAverage time.Duration `jsonapi:"attr,plan-duration-average"`
PolicyCheckFailures int `jsonapi:"attr,policy-check-failures"`
RunFailures int `jsonapi:"attr,run-failures"`
RunsCount int `jsonapi:"attr,workspace-kpis-runs-count"`
TagNames []string `jsonapi:"attr,tag-names"`
SettingOverwrites *WorkspaceSettingOverwrites `jsonapi:"attr,setting-overwrites"`
// Relations
AgentPool *AgentPool `jsonapi:"relation,agent-pool"`
CurrentRun *Run `jsonapi:"relation,current-run"`
CurrentStateVersion *StateVersion `jsonapi:"relation,current-state-version"`
Organization *Organization `jsonapi:"relation,organization"`
SSHKey *SSHKey `jsonapi:"relation,ssh-key"`
Outputs []*WorkspaceOutputs `jsonapi:"relation,outputs"`
Project *Project `jsonapi:"relation,project"`
Tags []*Tag `jsonapi:"relation,tags"`
CurrentConfigurationVersion *ConfigurationVersion `jsonapi:"relation,current-configuration-version,omitempty"`
LockedBy *LockedByChoice `jsonapi:"polyrelation,locked-by"`
Variables []*Variable `jsonapi:"relation,vars"`
TagBindings []*TagBinding `jsonapi:"relation,tag-bindings"`
// Deprecated: Use DataRetentionPolicyChoice instead.
DataRetentionPolicy *DataRetentionPolicy
// **Note: This functionality is only available in Terraform Enterprise.**
DataRetentionPolicyChoice *DataRetentionPolicyChoice `jsonapi:"polyrelation,data-retention-policy"`
// Links
Links map[string]interface{} `jsonapi:"links,omitempty"`
}
type WorkspaceOutputs struct {
ID string `jsonapi:"primary,workspace-outputs"`
Name string `jsonapi:"attr,name"`
Sensitive bool `jsonapi:"attr,sensitive"`
Type string `jsonapi:"attr,output-type"`
Value interface{} `jsonapi:"attr,value"`
}
// workspaceWithReadme is the same as a workspace but it has a readme.
type workspaceWithReadme struct {
ID string `jsonapi:"primary,workspaces"`
Readme *workspaceReadme `jsonapi:"relation,readme"`
}
// workspaceReadme contains the readme of the workspace.
type workspaceReadme struct {
ID string `jsonapi:"primary,workspace-readme"`
RawMarkdown string `jsonapi:"attr,raw-markdown"`
}
// VCSRepo contains the configuration of a VCS integration.
type VCSRepo struct {
Branch string `jsonapi:"attr,branch"`
DisplayIdentifier string `jsonapi:"attr,display-identifier"`
Identifier string `jsonapi:"attr,identifier"`
IngressSubmodules bool `jsonapi:"attr,ingress-submodules"`
OAuthTokenID string `jsonapi:"attr,oauth-token-id"`
GHAInstallationID string `jsonapi:"attr,github-app-installation-id"`
RepositoryHTTPURL string `jsonapi:"attr,repository-http-url"`
ServiceProvider string `jsonapi:"attr,service-provider"`
Tags bool `jsonapi:"attr,tags"`
TagsRegex string `jsonapi:"attr,tags-regex"`
WebhookURL string `jsonapi:"attr,webhook-url"`
}
// Note: the fields of this struct are bool pointers instead of bool values, in order to simplify support for
// future TFE versions that support *some but not all* of the inherited defaults that go-tfe knows about.
type WorkspaceSettingOverwrites struct {
ExecutionMode *bool `jsonapi:"attr,execution-mode"`
AgentPool *bool `jsonapi:"attr,agent-pool"`
}
// WorkspaceActions represents the workspace actions.
type WorkspaceActions struct {
IsDestroyable bool `jsonapi:"attr,is-destroyable"`
}
// WorkspacePermissions represents the workspace permissions.
type WorkspacePermissions struct {
CanDestroy bool `jsonapi:"attr,can-destroy"`
CanForceUnlock bool `jsonapi:"attr,can-force-unlock"`
CanLock bool `jsonapi:"attr,can-lock"`
CanManageRunTasks bool `jsonapi:"attr,can-manage-run-tasks"`
CanQueueApply bool `jsonapi:"attr,can-queue-apply"`
CanQueueDestroy bool `jsonapi:"attr,can-queue-destroy"`
CanQueueRun bool `jsonapi:"attr,can-queue-run"`
CanReadSettings bool `jsonapi:"attr,can-read-settings"`
CanUnlock bool `jsonapi:"attr,can-unlock"`
CanUpdate bool `jsonapi:"attr,can-update"`
CanUpdateVariable bool `jsonapi:"attr,can-update-variable"`
CanForceDelete *bool `jsonapi:"attr,can-force-delete"` // pointer b/c it will be useful to check if this property exists, as opposed to having it default to false
}
// WSIncludeOpt represents the available options for include query params.
// https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces#available-related-resources
type WSIncludeOpt string
const (
WSOrganization WSIncludeOpt = "organization"
WSCurrentConfigVer WSIncludeOpt = "current_configuration_version"
WSCurrentConfigVerIngress WSIncludeOpt = "current_configuration_version.ingress_attributes"
WSCurrentRun WSIncludeOpt = "current_run"
WSCurrentRunPlan WSIncludeOpt = "current_run.plan"
WSCurrentRunConfigVer WSIncludeOpt = "current_run.configuration_version"
WSCurrentrunConfigVerIngress WSIncludeOpt = "current_run.configuration_version.ingress_attributes"
WSLockedBy WSIncludeOpt = "locked_by"
WSReadme WSIncludeOpt = "readme"
WSOutputs WSIncludeOpt = "outputs"
WSCurrentStateVer WSIncludeOpt = "current-state-version"
WSProject WSIncludeOpt = "project"
)
// WorkspaceReadOptions represents the options for reading a workspace.
type WorkspaceReadOptions struct {
// Optional: A list of relations to include.
// https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces#available-related-resources
Include []WSIncludeOpt `url:"include,omitempty"`
}
// WorkspaceListOptions represents the options for listing workspaces.
type WorkspaceListOptions struct {
ListOptions
// Optional: A search string (partial workspace name) used to filter the results.
Search string `url:"search[name],omitempty"`
// Optional: A search string (comma-separated tag names) used to filter the results.
Tags string `url:"search[tags],omitempty"`
// Optional: A search string (comma-separated tag names to exclude) used to filter the results.
ExcludeTags string `url:"search[exclude-tags],omitempty"`
// Optional: A search on substring matching to filter the results.
WildcardName string `url:"search[wildcard-name],omitempty"`
// Optional: A filter string to list all the workspaces linked to a given project id in the organization.
ProjectID string `url:"filter[project][id],omitempty"`
// Optional: A filter string to list all the workspaces filtered by current run status.
CurrentRunStatus string `url:"filter[current-run][status],omitempty"`
// Optional: A filter string to list workspaces filtered by key/value tags.
// These are not annotated and therefore not encoded by go-querystring
TagBindings []*TagBinding
// Optional: A list of relations to include. See available resources https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces#available-related-resources
Include []WSIncludeOpt `url:"include,omitempty"`
// Optional: May sort on "name" (the default) and "current-run.created-at" (which sorts by the time of the current run)
// Prepending a hyphen to the sort parameter will reverse the order (e.g. "-name" to reverse the default order)
Sort string `url:"sort,omitempty"`
}
// WorkspaceCreateOptions represents the options for creating a new workspace.
type WorkspaceCreateOptions 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,workspaces"`
// Required when: execution-mode is set to agent. The ID of the agent pool
// belonging to the workspace's organization. This value must not be specified
// if execution-mode is set to remote or local or if operations is set to true.
AgentPoolID *string `jsonapi:"attr,agent-pool-id,omitempty"`
// Optional: Whether destroy plans can be queued on the workspace.
AllowDestroyPlan *bool `jsonapi:"attr,allow-destroy-plan,omitempty"`
// Optional: Whether to enable health assessments (drift detection etc.) for the workspace.
// Reference: https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces#create-a-workspace
// Requires remote execution mode, HCP Terraform Business entitlement, and a valid agent pool to work
AssessmentsEnabled *bool `jsonapi:"attr,assessments-enabled,omitempty"`
// Optional: Whether to automatically apply changes when a Terraform plan is successful.
AutoApply *bool `jsonapi:"attr,auto-apply,omitempty"`
// Optional: Whether to automatically apply changes for runs that are created by run triggers
// from another workspace.
AutoApplyRunTrigger *bool `jsonapi:"attr,auto-apply-run-trigger,omitempty"`
// Optional: The time after which an automatic destroy run will be queued
AutoDestroyAt jsonapi.NullableAttr[time.Time] `jsonapi:"attr,auto-destroy-at,iso8601,omitempty"`
// Optional: The period of time to wait after workspace activity to trigger a destroy run. The format
// should roughly match a Go duration string limited to days and hours, e.g. "24h" or "1d".
AutoDestroyActivityDuration jsonapi.NullableAttr[string] `jsonapi:"attr,auto-destroy-activity-duration,omitempty"`
// Optional: A description for the workspace.
Description *string `jsonapi:"attr,description,omitempty"`
// Optional: Which execution mode to use. Valid values are remote, local, and agent.
// When set to local, the workspace will be used for state storage only.
// This value must not be specified if operations is specified.
// 'agent' execution mode is not available in Terraform Enterprise.
ExecutionMode *string `jsonapi:"attr,execution-mode,omitempty"`
// Optional: Whether to filter runs based on the changed files in a VCS push. If
// enabled, the working directory and trigger prefixes describe a set of
// paths which must contain changes for a VCS push to trigger a run. If
// disabled, any push will trigger a run.
FileTriggersEnabled *bool `jsonapi:"attr,file-triggers-enabled,omitempty"`
GlobalRemoteState *bool `jsonapi:"attr,global-remote-state,omitempty"`
// Optional: The legacy TFE environment to use as the source of the migration, in the
// form organization/environment. Omit this unless you are migrating a legacy
// environment.
MigrationEnvironment *string `jsonapi:"attr,migration-environment,omitempty"`
// The name of the workspace, which can only include letters, numbers, -,
// and _. This will be used as an identifier and must be unique in the
// organization.
Name *string `jsonapi:"attr,name"`
// DEPRECATED. Whether the workspace will use remote or local execution mode.
// Use ExecutionMode instead.
Operations *bool `jsonapi:"attr,operations,omitempty"`
// Whether to queue all runs. Unless this is set to true, runs triggered by
// a webhook will not be queued until at least one run is manually queued.
QueueAllRuns *bool `jsonapi:"attr,queue-all-runs,omitempty"`
// Whether this workspace allows speculative plans. Setting this to false
// prevents HCP Terraform or the Terraform Enterprise instance from
// running plans on pull requests, which can improve security if the VCS
// repository is public or includes untrusted contributors.
SpeculativeEnabled *bool `jsonapi:"attr,speculative-enabled,omitempty"`
// BETA. A friendly name for the application or client creating this
// workspace. If set, this will be displayed on the workspace as
// "Created via <SOURCE NAME>".
SourceName *string `jsonapi:"attr,source-name,omitempty"`
// BETA. A URL for the application or client creating this workspace. This
// can be the URL of a related resource in another app, or a link to
// documentation or other info about the client.
SourceURL *string `jsonapi:"attr,source-url,omitempty"`
// BETA. Enable the experimental advanced run user interface.
// This only applies to runs using Terraform version 0.15.2 or newer,
// and runs executed using older versions will see the classic experience
// regardless of this setting.
StructuredRunOutputEnabled *bool `jsonapi:"attr,structured-run-output-enabled,omitempty"`
// The version of Terraform to use for this workspace. Upon creating a
// workspace, the latest version is selected unless otherwise specified.
TerraformVersion *string `jsonapi:"attr,terraform-version,omitempty"`
// List of repository-root-relative paths which list all locations to be
// tracked for changes. See FileTriggersEnabled above for more details.
TriggerPrefixes []string `jsonapi:"attr,trigger-prefixes,omitempty"`
// Optional: List of patterns used to match against changed files in order
// to decide whether to trigger a run or not.
TriggerPatterns []string `jsonapi:"attr,trigger-patterns,omitempty"`
// Settings for the workspace's VCS repository. If omitted, the workspace is
// created without a VCS repo. If included, you must specify at least the
// oauth-token-id and identifier keys below.
VCSRepo *VCSRepoOptions `jsonapi:"attr,vcs-repo,omitempty"`
// A relative path that Terraform will execute within. This defaults to the
// root of your repository and is typically set to a subdirectory matching the
// environment when multiple environments exist within the same repository.
WorkingDirectory *string `jsonapi:"attr,working-directory,omitempty"`
// A list of tags to attach to the workspace. If the tag does not already
// exist, it is created and added to the workspace.
Tags []*Tag `jsonapi:"relation,tags,omitempty"`
// Optional: Struct of booleans, which indicate whether the workspace
// specifies its own values for various settings. If you mark a setting as
// `false` in this struct, it will clear the workspace's existing value for
// that setting and defer to the default value that its project or
// organization provides.
//
// In general, it's not necessary to mark a setting as `true` in this
// struct; if you provide a literal value for a setting, HCP Terraform will
// automatically update its overwrites field to `true`. If you do choose to
// manually mark a setting as overwritten, you must provide a value for that
// setting at the same time.
SettingOverwrites *WorkspaceSettingOverwritesOptions `jsonapi:"attr,setting-overwrites,omitempty"`
// Associated Project with the workspace. If not provided, default project
// of the organization will be assigned to the workspace.
Project *Project `jsonapi:"relation,project,omitempty"`
// Associated TagBindings of the workspace.
TagBindings []*TagBinding `jsonapi:"relation,tag-bindings,omitempty"`
}
// TODO: move this struct out. VCSRepoOptions is used by workspaces, policy sets, and registry modules
// VCSRepoOptions represents the configuration options of a VCS integration.
type VCSRepoOptions struct {
Branch *string `json:"branch,omitempty"`
Identifier *string `json:"identifier,omitempty"`
IngressSubmodules *bool `json:"ingress-submodules,omitempty"`
OAuthTokenID *string `json:"oauth-token-id,omitempty"`
TagsRegex *string `json:"tags-regex,omitempty"`
GHAInstallationID *string `json:"github-app-installation-id,omitempty"`
}
type WorkspaceSettingOverwritesOptions struct {
// If false, the workspace will defer to its organization or project's DefaultExecutionMode value.
ExecutionMode *bool `json:"execution-mode,omitempty"`
// If false, the workspace will defer to its organization or project's DefaultAgentPool value.
AgentPool *bool `json:"agent-pool,omitempty"`
}
// WorkspaceUpdateOptions represents the options for updating a workspace.
type WorkspaceUpdateOptions 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,workspaces"`
// Required when: execution-mode is set to agent. The ID of the agent pool
// belonging to the workspace's organization. This value must not be specified
// if execution-mode is set to remote or local or if operations is set to true.
AgentPoolID *string `jsonapi:"attr,agent-pool-id,omitempty"`
// Optional: Whether destroy plans can be queued on the workspace.
AllowDestroyPlan *bool `jsonapi:"attr,allow-destroy-plan,omitempty"`
// Optional: Whether to enable health assessments (drift detection etc.) for the workspace.
// Reference: https://developer.hashicorp.com/terraform/cloud-docs/api-docs/workspaces#update-a-workspace
// Requires remote execution mode, HCP Terraform Business entitlement, and a valid agent pool to work
AssessmentsEnabled *bool `jsonapi:"attr,assessments-enabled,omitempty"`
// Optional: Whether to automatically apply changes when a Terraform plan is successful.
AutoApply *bool `jsonapi:"attr,auto-apply,omitempty"`
// Optional: Whether to automatically apply changes for runs that are created by run triggers
// from another workspace.
AutoApplyRunTrigger *bool `jsonapi:"attr,auto-apply-run-trigger,omitempty"`
// Optional: The time after which an automatic destroy run will be queued
AutoDestroyAt jsonapi.NullableAttr[time.Time] `jsonapi:"attr,auto-destroy-at,iso8601,omitempty"`
// Optional: The period of time to wait after workspace activity to trigger a destroy run. The format
// should roughly match a Go duration string limited to days and hours, e.g. "24h" or "1d".
AutoDestroyActivityDuration jsonapi.NullableAttr[string] `jsonapi:"attr,auto-destroy-activity-duration,omitempty"`
// Optional: A new name for the workspace, which can only include letters, numbers, -,
// and _. This will be used as an identifier and must be unique in the
// organization. Warning: Changing a workspace's name changes its URL in the
// API and UI.
Name *string `jsonapi:"attr,name,omitempty"`
// Optional: A description for the workspace.
Description *string `jsonapi:"attr,description,omitempty"`
// Optional: Which execution mode to use. Valid values are remote, local, and agent.
// When set to local, the workspace will be used for state storage only.
// This value must not be specified if operations is specified.
// 'agent' execution mode is not available in Terraform Enterprise.
ExecutionMode *string `jsonapi:"attr,execution-mode,omitempty"`
// Optional: Whether to filter runs based on the changed files in a VCS push. If
// enabled, the working directory and trigger prefixes describe a set of
// paths which must contain changes for a VCS push to trigger a run. If
// disabled, any push will trigger a run.
FileTriggersEnabled *bool `jsonapi:"attr,file-triggers-enabled,omitempty"`
// Optional:
GlobalRemoteState *bool `jsonapi:"attr,global-remote-state,omitempty"`
// DEPRECATED. Whether the workspace will use remote or local execution mode.
// Use ExecutionMode instead.
Operations *bool `jsonapi:"attr,operations,omitempty"`
// Optional: Whether to queue all runs. Unless this is set to true, runs triggered by
// a webhook will not be queued until at least one run is manually queued.
QueueAllRuns *bool `jsonapi:"attr,queue-all-runs,omitempty"`
// Optional: Whether this workspace allows speculative plans. Setting this to false
// prevents HCP Terraform or the Terraform Enterprise instance from
// running plans on pull requests, which can improve security if the VCS
// repository is public or includes untrusted contributors.
SpeculativeEnabled *bool `jsonapi:"attr,speculative-enabled,omitempty"`
// BETA. Enable the experimental advanced run user interface.
// This only applies to runs using Terraform version 0.15.2 or newer,
// and runs executed using older versions will see the classic experience
// regardless of this setting.
StructuredRunOutputEnabled *bool `jsonapi:"attr,structured-run-output-enabled,omitempty"`
// Optional: The version of Terraform to use for this workspace.
TerraformVersion *string `jsonapi:"attr,terraform-version,omitempty"`
// Optional: List of repository-root-relative paths which list all locations to be
// tracked for changes. See FileTriggersEnabled above for more details.
TriggerPrefixes []string `jsonapi:"attr,trigger-prefixes,omitempty"`
// Optional: List of patterns used to match against changed files in order
// to decide whether to trigger a run or not.
TriggerPatterns []string `jsonapi:"attr,trigger-patterns,omitempty"`
// Optional: To delete a workspace's existing VCS repo, specify null instead of an
// object. To modify a workspace's existing VCS repo, include whichever of
// the keys below you wish to modify. To add a new VCS repo to a workspace
// that didn't previously have one, include at least the oauth-token-id and
// identifier keys.
VCSRepo *VCSRepoOptions `jsonapi:"attr,vcs-repo,omitempty"`
// Optional: A relative path that Terraform will execute within. This defaults to the
// root of your repository and is typically set to a subdirectory matching
// the environment when multiple environments exist within the same
// repository.
WorkingDirectory *string `jsonapi:"attr,working-directory,omitempty"`
// Optional: Struct of booleans, which indicate whether the workspace
// specifies its own values for various settings. If you mark a setting as
// `false` in this struct, it will clear the workspace's existing value for
// that setting and defer to the default value that its project or
// organization provides.
//
// In general, it's not necessary to mark a setting as `true` in this
// struct; if you provide a literal value for a setting, HCP Terraform will
// automatically update its overwrites field to `true`. If you do choose to
// manually mark a setting as overwritten, you must provide a value for that
// setting at the same time.
SettingOverwrites *WorkspaceSettingOverwritesOptions `jsonapi:"attr,setting-overwrites,omitempty"`
// Associated Project with the workspace. If not provided, default project
// of the organization will be assigned to the workspace
Project *Project `jsonapi:"relation,project,omitempty"`
// Associated TagBindings of the project. Note that this will replace
// all existing tag bindings.
TagBindings []*TagBinding `jsonapi:"relation,tag-bindings,omitempty"`
}
// WorkspaceLockOptions represents the options for locking a workspace.
type WorkspaceLockOptions struct {
// Specifies the reason for locking the workspace.
Reason *string `jsonapi:"attr,reason,omitempty"`
}
// workspaceRemoveVCSConnectionOptions
type workspaceRemoveVCSConnectionOptions struct {
ID string `jsonapi:"primary,workspaces"`
VCSRepo *VCSRepoOptions `jsonapi:"attr,vcs-repo"`
}
// WorkspaceAssignSSHKeyOptions represents the options to assign an SSH key to
// a workspace.
type WorkspaceAssignSSHKeyOptions 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,workspaces"`
// The SSH key ID to assign.
SSHKeyID *string `jsonapi:"attr,id"`
}
// workspaceUnassignSSHKeyOptions represents the options to unassign an SSH key
// to a workspace.
type workspaceUnassignSSHKeyOptions 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,workspaces"`
// Must be nil to unset the currently assigned SSH key.
SSHKeyID *string `jsonapi:"attr,id"`
}
type RemoteStateConsumersListOptions struct {
ListOptions
}
// WorkspaceAddRemoteStateConsumersOptions represents the options for adding remote state consumers
// to a workspace.
type WorkspaceAddRemoteStateConsumersOptions struct {
// The workspaces to add as remote state consumers to the workspace.
Workspaces []*Workspace
}
// WorkspaceRemoveRemoteStateConsumersOptions represents the options for removing remote state
// consumers from a workspace.
type WorkspaceRemoveRemoteStateConsumersOptions struct {
// The workspaces to remove as remote state consumers from the workspace.
Workspaces []*Workspace
}
// WorkspaceUpdateRemoteStateConsumersOptions represents the options for
// updatintg remote state consumers from a workspace.
type WorkspaceUpdateRemoteStateConsumersOptions struct {
// The workspaces to update remote state consumers for the workspace.
Workspaces []*Workspace
}
type WorkspaceTagListOptions struct {
ListOptions
// A query string used to filter workspace tags.
// Any workspace tag with a name partially matching this value will be returned.
Query *string `url:"name,omitempty"`
}
type WorkspaceAddTagsOptions struct {
Tags []*Tag
}
type WorkspaceRemoveTagsOptions struct {
Tags []*Tag
}
// List all the workspaces within an organization.
func (s *workspaces) List(ctx context.Context, organization string, options *WorkspaceListOptions) (*WorkspaceList, error) {
if !validStringID(&organization) {
return nil, ErrInvalidOrg
}
if err := options.valid(); err != nil {
return nil, err
}
var tagFilters map[string][]string
if options != nil {
tagFilters = encodeTagFiltersAsParams(options.TagBindings)
}
// Encode parameters that cannot be encoded by go-querystring
u := fmt.Sprintf("organizations/%s/workspaces", url.PathEscape(organization))
req, err := s.client.NewRequestWithAdditionalQueryParams("GET", u, options, tagFilters)
if err != nil {
return nil, err
}
wl := &WorkspaceList{}
err = req.Do(ctx, wl)
if err != nil {
return nil, err
}
return wl, nil
}
func (s *workspaces) ListTagBindings(ctx context.Context, workspaceID string) ([]*TagBinding, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
u := fmt.Sprintf("workspaces/%s/tag-bindings", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
var list struct {
*Pagination
Items []*TagBinding
}
err = req.Do(ctx, &list)
if err != nil {
return nil, err
}
return list.Items, nil
}
func (s *workspaces) ListEffectiveTagBindings(ctx context.Context, workspaceID string) ([]*EffectiveTagBinding, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
u := fmt.Sprintf("workspaces/%s/effective-tag-bindings", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
var list struct {
*Pagination
Items []*EffectiveTagBinding
}
err = req.Do(ctx, &list)
if err != nil {
return nil, err
}
return list.Items, nil
}
// AddTagBindings adds or modifies the value of existing tag binding keys for a workspace.
func (s *workspaces) AddTagBindings(ctx context.Context, workspaceID string, options WorkspaceAddTagBindingsOptions) ([]*TagBinding, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf("workspaces/%s/tag-bindings", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("PATCH", u, options.TagBindings)
if err != nil {
return nil, err
}
var response = struct {
*Pagination
Items []*TagBinding
}{}
err = req.Do(ctx, &response)
return response.Items, err
}
// Create is used to create a new workspace.
func (s *workspaces) Create(ctx context.Context, organization string, options WorkspaceCreateOptions) (*Workspace, error) {
if !validStringID(&organization) {
return nil, ErrInvalidOrg
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf("organizations/%s/workspaces", url.PathEscape(organization))
req, err := s.client.NewRequest("POST", u, &options)
if err != nil {
return nil, err
}
w := &Workspace{}
err = req.Do(ctx, w)
if err != nil {
return nil, err
}
return w, nil
}
// Read a workspace by its name and organization name.
func (s *workspaces) Read(ctx context.Context, organization, workspace string) (*Workspace, error) {
return s.ReadWithOptions(ctx, organization, workspace, nil)
}
// ReadWithOptions reads a workspace by name and organization name with given options.
func (s *workspaces) ReadWithOptions(ctx context.Context, organization, workspace string, options *WorkspaceReadOptions) (*Workspace, error) {
if !validStringID(&organization) {
return nil, ErrInvalidOrg
}
if !validStringID(&workspace) {
return nil, ErrInvalidWorkspaceValue
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf(
"organizations/%s/workspaces/%s",
url.PathEscape(organization),
url.PathEscape(workspace),
)
req, err := s.client.NewRequest("GET", u, options)
if err != nil {
return nil, err
}
w := &Workspace{}
err = req.Do(ctx, w)
if err != nil {
return nil, err
}
// Manually populate the deprecated DataRetentionPolicy field
w.DataRetentionPolicy = w.DataRetentionPolicyChoice.ConvertToLegacyStruct()
// durations come over in ms
w.ApplyDurationAverage *= time.Millisecond
w.PlanDurationAverage *= time.Millisecond
return w, nil
}
// ReadByID reads a workspace by its ID.
func (s *workspaces) ReadByID(ctx context.Context, workspaceID string) (*Workspace, error) {
return s.ReadByIDWithOptions(ctx, workspaceID, nil)
}
// ReadByIDWithOptions reads a workspace by its ID with the given options.
func (s *workspaces) ReadByIDWithOptions(ctx context.Context, workspaceID string, options *WorkspaceReadOptions) (*Workspace, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
u := fmt.Sprintf("workspaces/%s", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("GET", u, options)
if err != nil {
return nil, err
}
w := &Workspace{}
err = req.Do(ctx, w)
if err != nil {
return nil, err
}
// Manually populate the deprecated DataRetentionPolicy field
if w.DataRetentionPolicyChoice != nil {
w.DataRetentionPolicy = w.DataRetentionPolicyChoice.ConvertToLegacyStruct()
}
// durations come over in ms
w.ApplyDurationAverage *= time.Millisecond
w.PlanDurationAverage *= time.Millisecond
return w, nil
}
// Readme gets the readme of a workspace by its ID.
func (s *workspaces) Readme(ctx context.Context, workspaceID string) (io.Reader, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
u := fmt.Sprintf("workspaces/%s?include=readme", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
r := &workspaceWithReadme{}
err = req.Do(ctx, r)
if err != nil {
return nil, err
}
if r.Readme == nil {
return nil, nil
}
return strings.NewReader(r.Readme.RawMarkdown), nil
}
// Update settings of an existing workspace.
func (s *workspaces) Update(ctx context.Context, organization, workspace string, options WorkspaceUpdateOptions) (*Workspace, error) {
if !validStringID(&organization) {
return nil, ErrInvalidOrg
}
if !validStringID(&workspace) {
return nil, ErrInvalidWorkspaceValue
}
if err := options.valid(); err != nil {
return nil, err
}
u := fmt.Sprintf(
"organizations/%s/workspaces/%s",
url.PathEscape(organization),
url.PathEscape(workspace),
)
req, err := s.client.NewRequest("PATCH", u, &options)
if err != nil {
return nil, err
}
w := &Workspace{}
err = req.Do(ctx, w)
if err != nil {
return nil, err
}
return w, nil
}
// UpdateByID updates the settings of an existing workspace.
func (s *workspaces) UpdateByID(ctx context.Context, workspaceID string, options WorkspaceUpdateOptions) (*Workspace, error) {
if !validStringID(&workspaceID) {
return nil, ErrInvalidWorkspaceID
}
u := fmt.Sprintf("workspaces/%s", url.PathEscape(workspaceID))
req, err := s.client.NewRequest("PATCH", u, &options)
if err != nil {
return nil, err
}
w := &Workspace{}
err = req.Do(ctx, w)
if err != nil {
return nil, err
}
return w, nil