This repository was archived by the owner on Nov 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathtfc_org.go
More file actions
447 lines (389 loc) · 12.5 KB
/
tfc_org.go
File metadata and controls
447 lines (389 loc) · 12.5 KB
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
package workspacehelper
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"net/url"
"os"
"reflect"
"strings"
tfc "github.com/hashicorp/go-tfe"
appv1alpha1 "github.com/hashicorp/terraform-k8s/api/v1alpha1"
"github.com/hashicorp/terraform-k8s/version"
"github.com/hashicorp/terraform/command/cliconfig"
)
var (
// AutoApply run to workspace
AutoApply = true
AgentPageSize = 100
)
// TerraformCloudClient has a TFC Client and organization
type TerraformCloudClient struct {
Client *tfc.Client
Organization string
SecretsMountPath string
}
func createTerraformConfig(address string, tfConfig *cliconfig.Config) (*tfc.Config, error) {
if len(address) == 0 {
address = tfc.DefaultAddress
}
u, err := url.Parse(address)
if err != nil {
return nil, fmt.Errorf("Not a valid Terraform Cloud or Enterprise URL, %v", err)
}
if u.Scheme == "" {
return nil, fmt.Errorf("Invalid Terraform Cloud or Enterprise URL. Please specify a scheme (http:// or https://)")
}
host := u.Host
if host == "" {
return nil, fmt.Errorf("Terraform Cloud or Enterprise URL hostname is ''. Invalid hostname")
}
if len(tfConfig.Credentials[host]) == 0 {
return nil, fmt.Errorf("Define token for %s", host)
}
httpClient := tfc.DefaultConfig().HTTPClient
transport := httpClient.Transport.(*http.Transport)
if transport.TLSClientConfig == nil {
transport.TLSClientConfig = &tls.Config{}
}
skipTLS := os.Getenv("TF_INSECURE")
if skipTLS != "" && strings.ToLower(skipTLS) != "false" {
transport.TLSClientConfig.InsecureSkipVerify = true
}
ua := fmt.Sprintf("terraform-k8s/%s", version.Version)
return &tfc.Config{
Address: address,
Token: fmt.Sprintf("%v", tfConfig.Credentials[host]["token"]),
Headers: http.Header{"User-Agent": []string{ua}},
HTTPClient: httpClient,
}, nil
}
// GetClient creates the configuration for Terraform Cloud
func (t *TerraformCloudClient) GetClient(tfEndpoint string) error {
tfConfig, diag := cliconfig.LoadConfig()
if diag.Err() != nil {
return diag.Err()
}
config, err := createTerraformConfig(tfEndpoint, tfConfig)
if err != nil {
return err
}
client, err := tfc.NewClient(config)
if err != nil {
return err
}
t.Client = client
return nil
}
// CheckOrganization looks for an organization
func (t *TerraformCloudClient) CheckOrganization() error {
_, err := t.Client.Organizations.Read(context.TODO(), t.Organization)
return err
}
func (t *TerraformCloudClient) SetTerraformVersion(workspace, terraformVersion string) error {
wsUpdateOptions := tfc.WorkspaceUpdateOptions{
TerraformVersion: &terraformVersion,
}
_, err := t.Client.Workspaces.Update(context.TODO(), t.Organization, workspace, wsUpdateOptions)
if err != nil {
return err
}
return nil
}
func (t *TerraformCloudClient) SetWorkingDirectory(workspace, workingDirectory string) error {
wsUpdateOptions := tfc.WorkspaceUpdateOptions{
WorkingDirectory: &workingDirectory,
}
_, err := t.Client.Workspaces.Update(context.TODO(), t.Organization, workspace, wsUpdateOptions)
if err != nil {
return err
}
return nil
}
// getAgentPoolID uses AgentPoolName to lookup and return AgentPoolID
func getAgentPoolID(specTFCAgentPoolName string, agentPools []*tfc.AgentPool) (*tfc.AgentPool, error) {
for _, agentPool := range agentPools {
if specTFCAgentPoolName == agentPool.Name {
return agentPool, nil
}
}
return nil, fmt.Errorf("No valid agent pools exist with name %v", specTFCAgentPoolName)
}
func (t *TerraformCloudClient) listAgentPools() ([]*tfc.AgentPool, error) {
options := tfc.AgentPoolListOptions{
ListOptions: tfc.ListOptions{PageSize: AgentPageSize},
}
agentpools, err := t.Client.AgentPools.List(context.TODO(), t.Organization, options)
if err != nil {
return nil, fmt.Errorf("Problem fetching agent pools %s", err)
}
return agentpools.Items, nil
}
func (t *TerraformCloudClient) updateAgentPoolID(instance *appv1alpha1.Workspace, workspace *tfc.Workspace) error {
var agentPoolID string
// When agent pool name provided, look it up otherwise set to id in spec
if instance.Spec.AgentPoolName != "" {
agentPools, err := t.listAgentPools()
agentPool, err := getAgentPoolID(instance.Spec.AgentPoolName, agentPools)
if err != nil {
return err
}
agentPoolID = agentPool.ID
} else if instance.Spec.AgentPoolID != "" {
agentPoolID = instance.Spec.AgentPoolID
}
if agentPoolID == workspace.AgentPoolID {
return nil
}
updateOptions := tfc.WorkspaceUpdateOptions{
AgentPoolID: &agentPoolID,
}
if agentPoolID != "" {
updateOptions.ExecutionMode = tfc.String("agent")
} else {
updateOptions.ExecutionMode = tfc.String("")
}
_, err := t.Client.Workspaces.Update(context.TODO(), t.Organization, workspace.Name, updateOptions)
if err != nil {
return err
}
return nil
}
// CheckWorkspace looks for a remote tfc workspace
func (t *TerraformCloudClient) CheckWorkspace(workspace string, instance *appv1alpha1.Workspace) (*tfc.Workspace, error) {
ws, err := t.Client.Workspaces.Read(context.TODO(), t.Organization, workspace)
if err != nil && err == tfc.ErrResourceNotFound {
id, wsErr := t.CreateWorkspace(workspace, instance)
if wsErr != nil {
return nil, wsErr
} else {
ws = &tfc.Workspace{ID: id}
err = nil
}
ws = &tfc.Workspace{ID: id}
} else if err != nil {
return nil, err
}
if instance.Spec.SSHKeyID != "" {
_, err = t.AssignWorkspaceSSHKey(ws.ID, instance.Spec.SSHKeyID)
if err != nil {
return nil, fmt.Errorf("Error while assigning ssh key to workspace: %s", err)
}
} else if ws.SSHKey != nil {
_, err = t.UnassignWorkspaceSSHKey(ws.ID)
if err != nil {
return nil, fmt.Errorf("Error while unassigning ssh key to workspace: %s", err)
}
}
if instance.Spec.TerraformVersion != ws.TerraformVersion {
err = t.SetTerraformVersion(workspace, instance.Spec.TerraformVersion)
if err != nil {
return nil, err
}
}
if instance.Spec.WorkingDirectory != ws.WorkingDirectory {
err = t.SetWorkingDirectory(workspace, instance.Spec.WorkingDirectory)
if err != nil {
return nil, err
}
}
if instance.Spec.AgentPoolID != ws.AgentPoolID {
err := t.updateAgentPoolID(instance, ws)
if err != nil {
return nil, fmt.Errorf("error while updating Agent Pool ID settings for workspace %q: %s", ws.Name, err)
}
}
return ws, err
}
// CreateWorkspace creates a Terraform Cloud Workspace that auto-applies
func (t *TerraformCloudClient) CreateWorkspace(workspace string, instance *appv1alpha1.Workspace) (string, error) {
var tfVersion string
if instance.Spec.TerraformVersion == "" {
tfVersion = "latest"
} else {
tfVersion = instance.Spec.TerraformVersion
}
options := tfc.WorkspaceCreateOptions{
AutoApply: &AutoApply,
Name: &workspace,
TerraformVersion: &tfVersion,
}
if instance.Spec.VCS != nil {
options.VCSRepo = &tfc.VCSRepoOptions{
Branch: &instance.Spec.VCS.Branch,
Identifier: &instance.Spec.VCS.RepoIdentifier,
IngressSubmodules: &instance.Spec.VCS.IngressSubmodules,
OAuthTokenID: &instance.Spec.VCS.TokenID,
}
}
if instance.Spec.AgentPoolID != "" {
options.AgentPoolID = &instance.Spec.AgentPoolID
options.ExecutionMode = tfc.String("agent")
} else if instance.Spec.AgentPoolName != "" {
agentPools, err := t.listAgentPools()
if err != nil {
return "", err
}
agentPool, err := getAgentPoolID(instance.Spec.AgentPoolName, agentPools)
if err != nil {
return "", err
}
options.AgentPoolID = &agentPool.ID
options.ExecutionMode = tfc.String("agent")
}
if instance.Spec.WorkingDirectory != "" {
options.WorkingDirectory = &instance.Spec.WorkingDirectory
}
ws, err := t.Client.Workspaces.Create(context.TODO(), t.Organization, options)
if err != nil {
return "", err
}
return ws.ID, nil
}
// GetSSHKeyByNameOrID Lookup provided Key ID by name or ID, return ID.
func (t *TerraformCloudClient) GetSSHKeyByNameOrID(SSHKeyID string) (string, error) {
sshKeys, err := t.Client.SSHKeys.List(context.TODO(), t.Organization, tfc.SSHKeyListOptions{})
if err != nil {
return "", err
}
for _, elem := range sshKeys.Items {
if elem.ID == SSHKeyID || elem.Name == SSHKeyID {
return elem.ID, nil
}
}
log.Error(tfc.ErrResourceNotFound, "No SSHKey found for "+SSHKeyID)
return "", tfc.ErrResourceNotFound
}
// AssignWorkspaceSSHKey to Terraform Cloud Workspace
func (t *TerraformCloudClient) AssignWorkspaceSSHKey(workspaceID string, SSHKeyID string) (string, error) {
sshKey, err := t.GetSSHKeyByNameOrID(SSHKeyID)
if err != nil {
return "", err
}
sshOptions := tfc.WorkspaceAssignSSHKeyOptions{
SSHKeyID: &sshKey,
}
ws, err := t.Client.Workspaces.AssignSSHKey(context.TODO(), workspaceID, sshOptions)
if err != nil {
return "", err
}
return ws.ID, nil
}
// UnassignWorkspaceSSHKey from Terraform Cloud Workspace
func (t *TerraformCloudClient) UnassignWorkspaceSSHKey(workspaceID string) (string, error) {
ws, err := t.Client.Workspaces.UnassignSSHKey(context.TODO(), workspaceID)
if err != nil {
return "", err
}
return ws.ID, nil
}
// CheckWorkspacebyID checks a workspace by ID
func (t *TerraformCloudClient) CheckWorkspacebyID(workspaceID string) error {
_, err := t.Client.Workspaces.ReadByID(context.TODO(), workspaceID)
return err
}
// DeleteWorkspace removes the workspace from Terraform Cloud
func (t *TerraformCloudClient) DeleteWorkspace(workspaceID string) error {
err := t.Client.Workspaces.DeleteByID(context.TODO(), workspaceID)
if err != nil {
return err
}
return nil
}
func compareNotifications(wsNotification *tfc.NotificationConfiguration, specNotification *appv1alpha1.Notification) bool {
if wsNotification.Name != specNotification.Name {
return false
}
log.Info(fmt.Sprintf("%#v vs %#v", wsNotification, specNotification))
if wsNotification.Token != specNotification.Token ||
wsNotification.URL != specNotification.URL ||
wsNotification.DestinationType != specNotification.Type ||
wsNotification.Enabled != specNotification.Enabled {
return false
}
if !reflect.DeepEqual(wsNotification.EmailAddresses, specNotification.Recipients) {
return false
}
var wsUserIDs []string
for _, user := range wsNotification.EmailUsers {
wsUserIDs = append(wsUserIDs, user.ID)
}
if !reflect.DeepEqual(wsNotification.Triggers, specNotification.Triggers) {
return false
}
return reflect.DeepEqual(wsUserIDs, specNotification.Users)
}
// Check Notification checks, and if necessary creates, the workspace's notifications
func (t *TerraformCloudClient) CheckNotifications(instance *appv1alpha1.Workspace) error {
workspaceID := instance.Status.WorkspaceID
notifications, err := t.Client.NotificationConfigurations.List(context.TODO(), workspaceID,
tfc.NotificationConfigurationListOptions{})
if err != nil {
return err
}
if len(notifications.Items) == 0 && len(instance.Spec.Notifications) == 0 {
return nil
}
var toRemove []*tfc.NotificationConfiguration
// Find notifications not defined in spec
for _, wsNotification := range notifications.Items {
found := false
for _, specNotification := range instance.Spec.Notifications {
if compareNotifications(wsNotification, specNotification) {
found = true
break
}
}
if !found {
toRemove = append(toRemove, wsNotification)
}
}
// Remove extra notifications
for _, notification := range toRemove {
err := t.Client.NotificationConfigurations.Delete(context.TODO(), notification.ID)
if err != nil {
return err
}
}
// refresh notifications list
notifications, err = t.Client.NotificationConfigurations.List(context.TODO(), workspaceID,
tfc.NotificationConfigurationListOptions{})
if err != nil {
return err
}
var toAdd []*appv1alpha1.Notification
// Find notifications missing from workspace
for _, specNotification := range instance.Spec.Notifications {
found := false
for _, wsNotification := range notifications.Items {
if wsNotification.Name == specNotification.Name {
found = true
break
}
}
if !found {
toAdd = append(toAdd, specNotification)
}
}
// Add missing notifications
for _, notification := range toAdd {
createOpts := tfc.NotificationConfigurationCreateOptions{
Name: ¬ification.Name,
DestinationType: ¬ification.Type,
Enabled: ¬ification.Enabled,
Token: ¬ification.Token,
URL: ¬ification.URL,
EmailAddresses: notification.Recipients,
Triggers: notification.Triggers,
}
for _, user := range notification.Users {
createOpts.EmailUsers = append(createOpts.EmailUsers, &tfc.User{ID: user})
}
_, err := t.Client.NotificationConfigurations.Create(context.TODO(), workspaceID, createOpts)
if err != nil {
return err
}
}
return nil
}