-
Notifications
You must be signed in to change notification settings - Fork 784
/
gcloud.go
1480 lines (1292 loc) · 38.2 KB
/
gcloud.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
package gke
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
osUser "os/user"
"github.com/jenkins-x/jx-logging/pkg/log"
"github.com/jenkins-x/jx/v2/pkg/kube/naming"
"github.com/jenkins-x/jx/v2/pkg/util"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
)
// KmsLocation indicates the location used by the Google KMS service
const KmsLocation = "global"
var (
// RequiredServiceAccountRoles the roles required to create a cluster with terraform
RequiredServiceAccountRoles = []string{"roles/owner"}
// KanikoServiceAccountRoles the roles required to run kaniko with GCS
KanikoServiceAccountRoles = []string{"roles/storage.admin",
"roles/storage.objectAdmin",
"roles/storage.objectCreator"}
// VeleroServiceAccountRoles the roles required to run velero with GCS
VeleroServiceAccountRoles = []string{
/* TODO
"roles/compute.disks.get",
"roles/compute.disks.create",
"roles/compute.disks.createSnapshot",
"roles/compute.snapshots.get",
"roles/compute.snapshots.create",
"roles/compute.snapshots.useReadOnly",
"roles/compute.snapshots.delete",
"roles/compute.zones.get",
*/
"roles/storage.admin",
"roles/storage.objectAdmin",
"roles/storage.objectCreator"}
)
// GCloud real implementation of the gcloud helper
type GCloud struct {
}
// Cluster struct to represent a cluster on gcloud
type Cluster struct {
Name string `json:"name,omitempty"`
ResourceLabels map[string]string `json:"resourceLabels,omitempty"`
Status string `json:"status,omitempty"`
Location string `json:"location,omitempty"`
}
type recordSet struct {
Kind string `json:"kind"`
Name string `json:"name"`
Rrdatas []string `json:"rrdatas"`
TTL int `json:"ttl"`
Type string `json:"type"`
}
// generateManagedZoneName constructs and returns a managed zone name using the domain value
func generateManagedZoneName(domain string) string {
var managedZoneName string
if domain != "" {
managedZoneName = strings.Replace(domain, ".", "-", -1)
return fmt.Sprintf("%s-zone", managedZoneName)
}
return ""
}
// getManagedZoneName checks for a given domain zone within the specified project and returns its name
func getManagedZoneName(projectID string, domain string) (string, error) {
args := []string{"dns",
"managed-zones",
fmt.Sprintf("--project=%s", projectID),
"list",
fmt.Sprintf("--filter=%s.", domain),
"--format=json",
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
return "", errors.Wrap(err, "executing gcloud dns managed-zones list command ")
}
type managedZone struct {
Name string `json:"name"`
}
var managedZones []managedZone
err = yaml.Unmarshal([]byte(output), &managedZones)
if err != nil {
return "", errors.Wrap(err, "unmarshalling gcloud response")
}
if len(managedZones) == 1 {
return managedZones[0].Name, nil
}
return "", nil
}
// CreateManagedZone creates a managed zone for the given domain in the specified project
func (g *GCloud) CreateManagedZone(projectID string, domain string) error {
managedZoneName, err := getManagedZoneName(projectID, domain)
if err != nil {
return errors.Wrap(err, "unable to determine whether managed zone exists")
}
if managedZoneName == "" {
log.Logger().Infof("Managed Zone doesn't exist for %s domain, creating...", domain)
managedZoneName := generateManagedZoneName(domain)
args := []string{"dns",
"managed-zones",
fmt.Sprintf("--project=%s", projectID),
"create",
managedZoneName,
"--dns-name",
fmt.Sprintf("%s.", domain),
"--description=managed-zone utilised by jx",
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "executing gcloud dns managed-zones list command ")
}
} else {
log.Logger().Infof("Managed Zone exists for %s domain.", domain)
}
return nil
}
// CreateDNSZone creates the DNS zone if it doesn't exist
// and returns the list of name servers for the given domain and project
func (g *GCloud) CreateDNSZone(projectID string, domain string) (string, []string, error) {
var managedZone, nameServers = "", []string{}
err := g.CreateManagedZone(projectID, domain)
if err != nil {
return "", []string{}, errors.Wrap(err, "while trying to creating a CloudDNS managed zone")
}
managedZone, nameServers, err = g.GetManagedZoneNameServers(projectID, domain)
if err != nil {
return "", []string{}, errors.Wrap(err, "while trying to retrieve the managed zone name servers")
}
// Update TTL to 60 for managed zone NS record
err = updateManagedZoneRecordTTL(projectID, domain, managedZone, "NS", 60)
if err != nil {
return "", []string{}, errors.Wrap(err, "when trying to update the managed zone NS record-set")
}
// Update TTL to 60 for managed zone SOA record
err = updateManagedZoneRecordTTL(projectID, domain, managedZone, "SOA", 60)
if err != nil {
return "", []string{}, errors.Wrap(err, "when trying to update the managed zone SOA record-set")
}
return managedZone, nameServers, nil
}
// GetManagedZoneNameServers retrieves a list of name servers associated with a zone
func (g *GCloud) GetManagedZoneNameServers(projectID string, domain string) (string, []string, error) {
var nameServers = []string{}
managedZoneName, err := getManagedZoneName(projectID, domain)
if err != nil {
return "", []string{}, errors.Wrap(err, "unable to determine whether managed zone exists")
}
if managedZoneName != "" {
log.Logger().Infof("Getting nameservers for %s domain", domain)
args := []string{"dns",
"managed-zones",
fmt.Sprintf("--project=%s", projectID),
"describe",
managedZoneName,
"--format=json",
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
type mz struct {
Name string `json:"name"`
NameServers []string `json:"nameServers"`
}
var managedZone mz
output, err := cmd.RunWithoutRetry()
if err != nil {
return "", []string{}, errors.Wrap(err, "executing gcloud dns managed-zones list command ")
}
err = json.Unmarshal([]byte(output), &managedZone)
if err != nil {
return "", []string{}, errors.Wrap(err, "unmarshalling gcloud response when returning managed-zone nameservers")
}
nameServers = managedZone.NameServers
} else {
log.Logger().Infof("Managed Zone doesn't exist for %s domain.", domain)
}
return managedZoneName, nameServers, nil
}
func getManagedZoneRecordSet(parentProject string, parentZone string, mzRecordSet recordSet) (recordSet, error) {
var googleRecordSet recordSet
args := []string{"dns",
"record-sets",
fmt.Sprintf("--project=%s", parentProject),
"list",
fmt.Sprintf("--name=%s", mzRecordSet.Name),
fmt.Sprintf("--zone=%s", parentZone),
fmt.Sprintf("--filter=type:%s", mzRecordSet.Type),
"--format=json",
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.Run()
if err != nil {
return googleRecordSet, errors.Wrap(err, "executing gcloud dns managed-zones list command")
}
var recordSets []recordSet
err = yaml.Unmarshal([]byte(output), &recordSets)
if err != nil {
return googleRecordSet, errors.Wrap(err, "unmarshalling gcloud response")
}
if len(recordSets) == 1 {
log.Logger().Infof("google dns record-set contains - domain: %s, with nameServers: %s\n", recordSets[0].Name, strings.Join(recordSets[0].Rrdatas, " "))
googleRecordSet = recordSets[0]
} else {
log.Logger().Debugf("No record-set or more than one record-set found for %s in %s", mzRecordSet.Name, parentZone)
}
return googleRecordSet, nil
}
func applyManagedZoneRecordTTL(parentProject string, parentZone string, googleRecordSet recordSet, ttl int) error {
if googleRecordSet.Name != "" {
// transaction start
startArgs := []string{"dns",
"record-sets",
fmt.Sprintf("--project=%s", parentProject),
"transaction",
"start",
fmt.Sprintf("--zone=%s", parentZone),
"--format=json",
}
startCmd := util.Command{
Name: "gcloud",
Args: startArgs,
}
_, err := startCmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "executing gcloud dns record-sets transaction start command")
}
// remove the previous record as it needs to be updated
removeArgs1 := []string{"dns",
"record-sets",
fmt.Sprintf("--project=%s", parentProject),
"transaction",
"remove",
}
removeArgs2 := []string{fmt.Sprintf("--name=%s", googleRecordSet.Name),
fmt.Sprintf("--ttl=%d", googleRecordSet.TTL),
fmt.Sprintf("--type=%s", googleRecordSet.Type),
fmt.Sprintf("--zone=%s", parentZone),
"--format=json",
}
removeArgs := append(removeArgs1, googleRecordSet.Rrdatas...)
removeArgs = append(removeArgs, removeArgs2...)
removeCmd := util.Command{
Name: "gcloud",
Args: removeArgs,
}
_, err = removeCmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "executing gcloud dns record-sets transaction remove command")
}
// transaction add
addArgs1 := []string{"dns",
"record-sets",
fmt.Sprintf("--project=%s", parentProject),
"transaction",
"add",
}
addArgs2 := []string{fmt.Sprintf("--name=%s", googleRecordSet.Name),
fmt.Sprintf("--ttl=%d", ttl),
fmt.Sprintf("--type=%s", googleRecordSet.Type),
fmt.Sprintf("--zone=%s", parentZone),
"--format=json",
}
addArgs := append(addArgs1, googleRecordSet.Rrdatas...)
addArgs = append(addArgs, addArgs2...)
addCmd := util.Command{
Name: "gcloud",
Args: addArgs,
}
_, err = addCmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "executing gcloud dns record-sets transaction add command")
}
// transaction execute
executeArgs := []string{"dns",
"record-sets",
fmt.Sprintf("--project=%s", parentProject),
"transaction",
"execute",
fmt.Sprintf("--zone=%s", parentZone),
"--format=json",
}
executeCmd := util.Command{
Name: "gcloud",
Args: executeArgs,
}
_, err = executeCmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "executing gcloud dns record-sets transaction start command")
}
}
return nil
}
func updateManagedZoneRecordTTL(projectID string, domain string, managedZone string, dnsType string, ttl int) error {
var managedZoneRecord recordSet
managedZoneRecord.Name = addDomainSuffix(domain)
managedZoneRecord.Type = dnsType
managedZoneRecord.TTL = ttl
managedZoneRecordSet, err := getManagedZoneRecordSet(projectID, managedZone, managedZoneRecord)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("when retrieving the '%s' record-set of type '%s'", domain, dnsType))
}
err = applyManagedZoneRecordTTL(projectID, managedZone, managedZoneRecordSet, 60)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("when updating the '%s' record-set of type '%s'", domain, dnsType))
}
return nil
}
// ClusterZone retrives the zone of GKE cluster description
func (g *GCloud) ClusterZone(cluster string) (string, error) {
args := []string{"container",
"clusters",
"describe",
cluster}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
return "", err
}
zone, err := parseClusterZone(output)
if err != nil {
return "", err
}
return zone, nil
}
func parseClusterZone(clusterInfo string) (string, error) {
ci := struct {
Zone string `json:"zone"`
}{}
err := yaml.Unmarshal([]byte(clusterInfo), &ci)
if err != nil {
return "", errors.Wrap(err, "extracting cluster zone from cluster info")
}
return ci.Zone, nil
}
type nodeConfig struct {
OauthScopes []string `json:"oauthScopes"`
}
func parseScopes(clusterInfo string) ([]string, error) {
ci := struct {
NodeConfig nodeConfig `json:"nodeConfig"`
}{}
err := yaml.Unmarshal([]byte(clusterInfo), &ci)
if err != nil {
return nil, errors.Wrap(err, "extracting cluster oauthScopes from cluster info")
}
return ci.NodeConfig.OauthScopes, nil
}
// BucketExists checks if a Google Storage bucket exists
func (g *GCloud) BucketExists(projectID string, bucketName string) (bool, error) {
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"ls"}
if projectID != "" {
args = append(args, "-p")
args = append(args, projectID)
}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
output, err := cmd.Run()
if err != nil {
log.Logger().Infof("Error checking bucket exists: %s, %s", output, err)
return false, err
}
return strings.Contains(output, fullBucketName), nil
}
// ListObjects checks if a Google Storage bucket exists
func (g *GCloud) ListObjects(bucketName string, path string) ([]string, error) {
fullBucketName := fmt.Sprintf("gs://%s/%s", bucketName, path)
args := []string{"ls", fullBucketName}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
log.Logger().Infof("Error checking bucket exists: %s, %s", output, err)
return []string{}, err
}
return strings.Split(output, "\n"), nil
}
// CreateBucket creates a new Google Storage bucket
func (g *GCloud) CreateBucket(projectID string, bucketName string, location string) error {
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"mb", "-l", location}
if projectID != "" {
args = append(args, "-p")
args = append(args, projectID)
}
args = append(args, fullBucketName)
cmd := util.Command{
Name: "gsutil",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
log.Logger().Infof("Error creating bucket: %s, %s", output, err)
return err
}
return nil
}
//AddBucketLabel adds a label to a Google Storage bucket
func (g *GCloud) AddBucketLabel(bucketName string, label string) {
found := g.FindBucket(bucketName)
if found && label != "" {
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"label", "ch", "-l", label}
args = append(args, fullBucketName)
cmd := util.Command{
Name: "gsutil",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
log.Logger().Infof("Error adding bucket label: %s, %s", output, err)
}
}
}
// FindBucket finds a Google Storage bucket
func (g *GCloud) FindBucket(bucketName string) bool {
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"list", "-b", fullBucketName}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return false
}
return true
}
// DeleteAllObjectsInBucket deletes all objects in a Google Storage bucket
func (g *GCloud) DeleteAllObjectsInBucket(bucketName string) error {
found := g.FindBucket(bucketName)
if !found {
return nil // nothing to delete
}
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"-m", "rm", "-r", fullBucketName}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return err
}
return nil
}
// StreamTransferFileFromBucket will perform a stream transfer from the GCS bucket to stdout and return a scanner
// with the piped result
func StreamTransferFileFromBucket(fullBucketURL string) (io.ReadCloser, error) {
bucketAccessible, err := isBucketAccessible(fullBucketURL)
if !bucketAccessible || err != nil {
return nil, errors.Wrap(err, "can't access bucket")
}
args := []string{"cp", fullBucketURL, "-"}
cmd := exec.Command("gsutil", args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Wrap(err, "can't get cmd stdout")
}
err = cmd.Start()
if err != nil {
return nil, errors.Wrap(err, "error streaming the logs from bucket")
}
return stdout, nil
}
func isBucketAccessible(bucketURL string) (bool, error) {
args := []string{"stat", bucketURL}
cmd := exec.Command("gsutil", args...)
out, err := cmd.CombinedOutput()
if err != nil {
return false, errors.New(string(out))
}
return true, nil
}
// DeleteBucket deletes a Google storage bucket
func (g *GCloud) DeleteBucket(bucketName string) error {
found := g.FindBucket(bucketName)
if !found {
return nil // nothing to delete
}
fullBucketName := fmt.Sprintf("gs://%s", bucketName)
args := []string{"rb", fullBucketName}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return err
}
return nil
}
// GetRegionFromZone parses the region from a GCP zone name. TODO: Return an error if the format of the zone is not correct
func GetRegionFromZone(zone string) string {
firstDash := strings.Index(zone, "-")
lastDash := strings.LastIndex(zone, "-")
if firstDash == lastDash { // It's a region, not a zone
return zone
}
return zone[0:lastDash]
}
// FindServiceAccount checks if a service account exists
func (g *GCloud) FindServiceAccount(serviceAccount string, projectID string) bool {
args := []string{"iam",
"service-accounts",
"list",
"--filter",
serviceAccount,
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.Run()
if err != nil {
return false
}
if output == "Listed 0 items." {
return false
}
return true
}
// GetOrCreateServiceAccount retrieves or creates a GCP service account. It will return the path to the file where the service
// account token is stored
func (g *GCloud) GetOrCreateServiceAccount(serviceAccount string, projectID string, clusterConfigDir string, roles []string) (string, error) {
if projectID == "" {
return "", errors.New("cannot get/create a service account without a projectId")
}
found := g.FindServiceAccount(serviceAccount, projectID)
if !found {
log.Logger().Infof("Unable to find service account %s, checking if we have enough permission to create", util.ColorInfo(serviceAccount))
// if it doesn't check to see if we have permissions to create (assign roles) to a service account
hasPerm, err := g.CheckPermission("resourcemanager.projects.setIamPolicy", projectID)
if err != nil {
return "", err
}
if !hasPerm {
return "", errors.New("User does not have the required role 'resourcemanager.projects.setIamPolicy' to configure a service account")
}
// create service
log.Logger().Infof("Creating service account %s", util.ColorInfo(serviceAccount))
args := []string{"iam",
"service-accounts",
"create",
serviceAccount,
"--project",
projectID,
"--display-name",
serviceAccount}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err = cmd.RunWithoutRetry()
if err != nil {
return "", err
}
// assign roles to service account
for _, role := range roles {
log.Logger().Infof("Assigning role %s", role)
args = []string{"projects",
"add-iam-policy-binding",
projectID,
"--member",
fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", serviceAccount, projectID),
"--role",
role,
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.Run()
if err != nil {
return "", err
}
}
} else {
log.Logger().Info("Service Account exists")
}
err := os.MkdirAll(clusterConfigDir, os.ModePerm)
if err != nil {
return "", errors.Wrapf(err, "Failed to create directory: %s", clusterConfigDir)
}
keyPath := filepath.Join(clusterConfigDir, fmt.Sprintf("%s.key.json", serviceAccount))
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
log.Logger().Info("Downloading service account key")
err := g.CreateServiceAccountKey(serviceAccount, projectID, keyPath)
if err != nil {
log.Logger().Infof("Exceeds the maximum number of keys on service account %s",
util.ColorInfo(serviceAccount))
err := g.CleanupServiceAccountKeys(serviceAccount, projectID)
if err != nil {
return "", errors.Wrap(err, "cleaning up the service account keys")
}
err = g.CreateServiceAccountKey(serviceAccount, projectID, keyPath)
if err != nil {
return "", errors.Wrap(err, "creating service account key")
}
}
} else {
log.Logger().Info("Key already exists")
}
return keyPath, nil
}
// ConfigureBucketRoles gives the given roles to the given service account
func (g *GCloud) ConfigureBucketRoles(projectID string, serviceAccount string, bucketURL string, roles []string) error {
member := fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", serviceAccount, projectID)
bindings := bucketMemberRoles{}
for _, role := range roles {
bindings.Bindings = append(bindings.Bindings, memberRole{
Members: []string{member},
Role: role,
})
}
file, err := ioutil.TempFile("", "gcp-iam-roles-")
if err != nil {
return errors.Wrapf(err, "failed to create temp file")
}
fileName := file.Name()
data, err := json.Marshal(&bindings)
if err != nil {
return errors.Wrapf(err, "failed to convert bindings %#v to JSON", bindings)
}
log.Logger().Infof("created json %s", string(data))
err = ioutil.WriteFile(fileName, data, util.DefaultWritePermissions)
if err != nil {
return errors.Wrapf(err, "failed to save bindings %#v to JSON file %s", bindings, fileName)
}
log.Logger().Infof("generated IAM bindings file %s", fileName)
args := []string{
"-m",
"iam",
"set",
"-a",
fileName,
bucketURL,
}
cmd := util.Command{
Name: "gsutil",
Args: args,
}
log.Logger().Infof("running: gsutil %s", strings.Join(args, " "))
_, err = cmd.Run()
if err != nil {
return err
}
return nil
}
type bucketMemberRoles struct {
Bindings []memberRole `json:"bindings"`
}
type memberRole struct {
Members []string `json:"members"`
Role string `json:"role"`
}
// CreateServiceAccountKey creates a new service account key and downloads into the given file
func (g *GCloud) CreateServiceAccountKey(serviceAccount string, projectID string, keyPath string) error {
args := []string{"iam",
"service-accounts",
"keys",
"create",
keyPath,
"--iam-account",
fmt.Sprintf("%s@%s.iam.gserviceaccount.com", serviceAccount, projectID),
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return errors.Wrap(err, "creating a new service account key")
}
return nil
}
// GetServiceAccountKeys returns all keys of a service account
func (g *GCloud) GetServiceAccountKeys(serviceAccount string, projectID string) ([]string, error) {
keys := []string{}
account := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", serviceAccount, projectID)
args := []string{"iam",
"service-accounts",
"keys",
"list",
"--iam-account",
account,
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
return keys, errors.Wrapf(err, "listing the keys of the service account '%s'", account)
}
scanner := bufio.NewScanner(strings.NewReader(output))
// Skip the first line with the header information
scanner.Scan()
for scanner.Scan() {
keyFields := strings.Fields(scanner.Text())
if len(keyFields) > 0 {
keys = append(keys, keyFields[0])
}
}
return keys, nil
}
// ListClusters returns the clusters in a GKE project
func (g *GCloud) ListClusters(region string, projectID string) ([]Cluster, error) {
args := []string{"container", "clusters", "list", "--region=" + region, "--format=json", "--quiet"}
if projectID != "" {
args = append(args, "--project="+projectID)
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
return nil, err
}
clusters := make([]Cluster, 0)
err = json.Unmarshal([]byte(output), &clusters)
if err != nil {
return nil, err
}
return clusters, nil
}
// LoadGkeCluster load a gke cluster from a GKE project
func (g *GCloud) LoadGkeCluster(region string, projectID string, clusterName string) (*Cluster, error) {
args := []string{"container", "clusters", "describe", clusterName, "--region=" + region, "--format=json", "--quiet"}
if projectID != "" {
args = append(args, "--project="+projectID)
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
output, err := cmd.RunWithoutRetry()
if err != nil {
return nil, err
}
cluster := &Cluster{}
err = json.Unmarshal([]byte(output), cluster)
if err != nil {
return nil, err
}
return cluster, nil
}
// UpdateGkeClusterLabels updates labesl for a gke cluster
func (g *GCloud) UpdateGkeClusterLabels(region string, projectID string, clusterName string, labels []string) error {
args := []string{"container", "clusters", "update", clusterName, "--quiet", "--update-labels=" + strings.Join(labels, ",") + ""}
if region != "" {
args = append(args, "--region="+region)
}
if projectID != "" {
args = append(args, "--project="+projectID)
}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()
return err
}
// DeleteServiceAccountKey deletes a service account key
func (g *GCloud) DeleteServiceAccountKey(serviceAccount string, projectID string, key string) error {
account := fmt.Sprintf("%s@%s.iam.gserviceaccount.com", serviceAccount, projectID)
args := []string{"iam",
"service-accounts",
"keys",
"delete",
key,
"--iam-account",
account,
"--project",
projectID,
"--quiet"}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return errors.Wrapf(err, "deleting the key '%s'from service account '%s'", key, account)
}
return nil
}
// CleanupServiceAccountKeys remove all keys from given service account
func (g *GCloud) CleanupServiceAccountKeys(serviceAccount string, projectID string) error {
keys, err := g.GetServiceAccountKeys(serviceAccount, projectID)
if err != nil {
return errors.Wrap(err, "retrieving the service account keys")
}
log.Logger().Infof("Cleaning up the keys of the service account %s", util.ColorInfo(serviceAccount))
for _, key := range keys {
err := g.DeleteServiceAccountKey(serviceAccount, projectID, key)
if err != nil {
log.Logger().Infof("Cannot delete the key %s from service account %s: %v",
util.ColorWarning(key), util.ColorInfo(serviceAccount), err)
} else {
log.Logger().Infof("Key %s was removed form service account %s",
util.ColorInfo(key), util.ColorInfo(serviceAccount))
}
}
return nil
}
// DeleteServiceAccount deletes a service account and its role bindings
func (g *GCloud) DeleteServiceAccount(serviceAccount string, projectID string, roles []string) error {
found := g.FindServiceAccount(serviceAccount, projectID)
if !found {
return nil // nothing to delete
}
// remove roles to service account
for _, role := range roles {
log.Logger().Infof("Removing role %s", role)
args := []string{"projects",
"remove-iam-policy-binding",
projectID,
"--member",
fmt.Sprintf("serviceAccount:%s@%s.iam.gserviceaccount.com", serviceAccount, projectID),
"--role",
role,
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return err
}
}
args := []string{"iam",
"service-accounts",
"delete",
fmt.Sprintf("%s@%s.iam.gserviceaccount.com", serviceAccount, projectID),
"--project",
projectID}
cmd := util.Command{
Name: "gcloud",
Args: args,
}
_, err := cmd.RunWithoutRetry()