-
Notifications
You must be signed in to change notification settings - Fork 35
/
px-deploy.go
2019 lines (1805 loc) · 77.1 KB
/
px-deploy.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 main
import (
"bufio"
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unicode/utf8"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcegraph/armresourcegraph"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/go-yaml/yaml"
"github.com/google/uuid"
version_hashicorp "github.com/hashicorp/go-version"
"github.com/imdario/mergo"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
type Config struct {
Name string
Template string
Cloud string
Aws_Region string
Gcp_Region string
Azure_Region string
Platform string
Clusters string
Nodes string
K8s_Version string
Px_Version string
Stop_After string
Post_Script string
DryRun bool
Lock bool
Aws_Type string
Aws_Ebs string
Aws_Tags string
Eks_Version string
Tags string
Aws_Access_Key_Id string
Aws_Secret_Access_Key string
Gcp_Type string
Gcp_Disks string
Gcp_Zone string
Gcp_Project string
Gcp_Auth_Json string
Gke_Version string
Azure_Type string
Azure_Disks string
Azure_Client_Id string
Azure_Client_Secret string
Azure_Subscription_Id string
Azure_Tenant_Id string
Aks_Version string
Vsphere_Host string
Vsphere_Compute_Resource string
Vsphere_Resource_Pool string
Vsphere_User string
Vsphere_Password string
Vsphere_Template string
Vsphere_Datastore string
Vsphere_Datacenter string
Vsphere_Folder string
Vsphere_Disks string
Vsphere_Network string
Vsphere_Memory string
Vsphere_Cpu string
Vsphere_Repo string
Vsphere_Dns string
Vsphere_Gw string
Vsphere_Node_Ip string
Vsphere_Nodemap map[string]string
Scripts []string
Description string
Env map[string]string
Cluster []Config_Cluster
Ocp4_Version string
Ocp4_Pull_Secret string
Ocp4_Domain string
Aws__Vpc string `yaml:"aws__vpc,omitempty"`
Gcp__Vpc string `yaml:"gcp__vpc,omitempty"`
Aws__Sg string `yaml:"aws__sg,omitempty"`
Aws__Subnet string `yaml:"aws__subnet,omitempty"`
Aws__Gw string `yaml:"aws__gw,omitempty"`
Aws__Routetable string `yaml:"aws__routetable,omitempty"`
Aws__Ami string `yaml:"aws__ami,omitempty"`
Gcp__Project string `yaml:"gcp__project,omitempty"`
Gcp__Key string `yaml:"gcp__key,omitempty"`
Azure__Group string `yaml:"azure__group,omitempty"`
Vsphere__Userdata string `yaml:"vsphere__userdata,omitempty"`
Ssh_Pub_Key string
Run_Predelete bool
}
type Config_Cluster struct {
Id int
Scripts []string
Instance_Type string
Nodes string
}
type Deployment_Status_Return struct {
cluster int
status string
}
type Predelete_Status_Return struct {
node string
success bool
}
var Reset = "\033[0m"
var White = "\033[97m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var testingName, testingTemplate string
var wg sync.WaitGroup
func main() {
var createName, createTemplate, createRegion, createEnv, connectName, kubeconfigName, destroyName, statusName, historyNumber string
var destroyAll, destroyClear, destroyForce bool
var flags Config
os.Chdir("/px-deploy/.px-deploy")
rootCmd := &cobra.Command{Use: "px-deploy"}
cmdCreate := &cobra.Command{
Use: "create",
Short: "Creates a deployment",
Long: "Creates a deployment",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("%v%v", check_version(), Reset)
if len(args) > 0 {
die("Invalid arguments")
}
config := parse_yaml("defaults.yml")
// should be there by default
// we dont put in into defaults.yml as it defines a path within container
config.Gcp_Auth_Json = "/px-deploy/.px-deploy/gcp.json"
if config.Aws_Tags != "" {
fmt.Printf("Parameter 'aws_tags: %s' is deprecated and will be ignored. Please change to 'tags: %s' in ~/.px-deploy/defaults.yml \n", config.Aws_Tags, config.Aws_Tags)
}
check_for_recommended_settings(&config)
prepare_error := prepare_deployment(&config, &flags, createName, createEnv, createTemplate, createRegion)
if prepare_error != "" {
die(prepare_error)
} else {
if !create_deployment(config) {
fmt.Printf("%s creation of deployment failed %s \n", Red, Reset)
os.Exit(1)
}
os.Chdir("/px-deploy/vagrant")
os.Setenv("deployment", config.Name)
}
},
}
cmdDestroy := &cobra.Command{
Use: "destroy",
Short: "Destroys a deployment",
Long: "Destroys a deployment",
Run: func(cmd *cobra.Command, args []string) {
if destroyAll {
if destroyClear {
die("--clear is not supported with -a")
}
if destroyName != "" {
die("Specify either -a or -n, not both")
}
filepath.Walk("deployments", func(file string, info os.FileInfo, err error) error {
if info.Mode()&os.ModeDir != 0 {
return nil
}
config := parse_yaml(file)
if _, err := os.Stat("tf-deployments/" + config.Name + "/" + config.Name + ".lock"); err == nil {
fmt.Printf("%s deployment %s is locked.\nPlease unlock using 'px-deploy unlock -n %s' first%s\n", Yellow, config.Name, config.Name, Reset)
} else if errors.Is(err, os.ErrNotExist) {
destroy_deployment(config.Name, destroyForce)
} else {
die(err.Error())
}
return nil
})
} else {
if destroyName == "" {
die("Must specify deployment to destroy")
}
if _, err := os.Stat("tf-deployments/" + destroyName + "/" + destroyName + ".lock"); err == nil {
fmt.Printf("%s deployment %s is locked.\nPlease unlock using 'px-deploy unlock -n %s' first%s\n", Yellow, destroyName, destroyName, Reset)
} else if errors.Is(err, os.ErrNotExist) {
if destroyClear {
destroy_clear(destroyName)
} else {
destroy_deployment(destroyName, destroyForce)
}
} else {
die(err.Error())
}
}
},
}
cmdConnect := &cobra.Command{
Use: "connect -n name [ command ]",
Short: "Connects to a deployment",
Long: "Connects to the first master node as root, and executes optional command",
Run: func(cmd *cobra.Command, args []string) {
config := parse_yaml("deployments/" + connectName + ".yml")
ip := get_ip(connectName)
command := ""
if len(args) > 0 {
command = args[0]
}
syscall.Exec("/usr/bin/ssh", []string{"ssh", "-oLoglevel=ERROR", "-oStrictHostKeyChecking=no", "-i", "keys/id_rsa." + config.Cloud + "." + config.Name, "root@" + ip, command}, os.Environ())
},
}
cmdKubeconfig := &cobra.Command{
Use: "kubeconfig -n name",
Short: "Downloads kubeconfigs from clusters",
Long: "Downloads kubeconfigs from clusters",
Run: func(cmd *cobra.Command, args []string) {
config := parse_yaml("deployments/" + kubeconfigName + ".yml")
ip := get_ip(kubeconfigName)
clusters, _ := strconv.Atoi(config.Clusters)
for c := 1; c <= clusters; c++ {
cmd := exec.Command("bash", "-c", "ssh -oLoglevel=ERROR -oStrictHostKeyChecking=no -i keys/id_rsa."+config.Cloud+"."+config.Name+" root@"+ip+" ssh master-"+strconv.Itoa(c)+" cat /root/.kube/config")
kubeconfig, err := cmd.Output()
if err != nil {
die(err.Error())
}
err = os.WriteFile("kubeconfig/"+config.Name+"."+strconv.Itoa(c), kubeconfig, 0644)
if err != nil {
die(err.Error())
}
}
},
}
cmdList := &cobra.Command{
Use: "list",
Short: "Lists available deployments",
Long: "Lists available deployments",
Run: func(cmd *cobra.Command, args []string) {
var data [][]string
filepath.Walk("deployments", func(file string, info os.FileInfo, err error) error {
if info.Mode()&os.ModeDir != 0 {
return nil
}
if !strings.HasSuffix(file, ".yml") {
return nil
}
config := parse_yaml(file)
var region string
switch config.Cloud {
case "aws":
region = config.Aws_Region
case "gcp":
region = config.Gcp_Region
case "azure":
region = config.Azure_Region
case "vsphere":
region = config.Vsphere_Compute_Resource
}
if config.Name == "" {
config.Name = Red + "UNKNOWN" + Reset
} else {
if config.Template == "" {
config.Template = "<None>"
}
}
data = append(data, []string{config.Name, config.Cloud, region, config.Platform, config.Template, config.Clusters, config.Nodes, info.ModTime().Format(time.RFC3339)})
return nil
})
print_table([]string{"Deployment", "Cloud", "Region", "Platform", "Template", "Clusters", "Nodes/Cl", "Created"}, data)
},
}
cmdTemplates := &cobra.Command{
Use: "templates",
Short: "Lists available templates",
Long: "Lists available templates",
Run: func(cmd *cobra.Command, args []string) {
list_templates()
},
}
cmdUnlock := &cobra.Command{
Use: "unlock",
Short: "Unlock deployment",
Long: "Unlock deployment",
Run: func(cmd *cobra.Command, args []string) {
if err := os.Remove("tf-deployments/" + statusName + "/" + statusName + ".lock"); err == nil {
fmt.Printf("%sunlocked deployment %s\nyou can run 'px-deploy destroy -n %s' now%s\n", Green, statusName, statusName, Reset)
} else if errors.Is(err, os.ErrNotExist) {
fmt.Printf("%slockfile for deployment %s does not exist%s\n", Yellow, statusName, Reset)
} else {
panic(err)
}
},
}
cmdStatus := &cobra.Command{
Use: "status",
Short: "Returns status / IP of a deployment",
Long: "Returns status / IP of a deployment",
Run: func(cmd *cobra.Command, args []string) {
config := parse_yaml("deployments/" + statusName + ".yml")
Clusters, _ := strconv.Atoi(config.Clusters)
clusterstatus := make(chan Deployment_Status_Return, Clusters)
wg.Add(Clusters)
for c := 1; c <= Clusters; c++ {
go get_deployment_status(&config, c, clusterstatus)
}
wg.Wait()
close(clusterstatus)
m := make(map[int]string)
for elem := range clusterstatus {
m[elem.cluster] = elem.status
}
for i := 1; i <= Clusters; i++ {
fmt.Printf(m[i])
}
},
}
cmdCompletion := &cobra.Command{
Use: "completion",
Short: "Generates bash completion scripts",
Long: `To load completion run
. <(px-deploy completion)`,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenBashCompletion(os.Stdout)
},
}
cmdVsphereInit := &cobra.Command{
Use: "vsphere-init",
Short: "Creates vSphere template",
Long: "Creates vSphere template",
Run: func(cmd *cobra.Command, args []string) {
vsphere_init()
},
}
cmdVsphereCheckTemplateVersion := &cobra.Command{
Use: "vsphere-check-template",
Short: "Checks version of vSphere template",
Long: "Checks version of vSphere template",
Run: func(cmd *cobra.Command, args []string) {
vsphere_check_templateversion(statusName)
},
}
cmdVersion := &cobra.Command{
Use: "version",
Short: "Displays version",
Long: "Displays version",
Run: func(cmd *cobra.Command, args []string) {
version()
},
}
cmdHistory := &cobra.Command{
Use: "history [ -n <ID> ]",
Short: "Displays history or inspects historical deployment",
Long: "Displays history or inspects historical deployment",
Run: func(cmd *cobra.Command, args []string) {
history(historyNumber)
},
}
defaults := parse_yaml("defaults.yml")
cmdCreate.Flags().StringVarP(&createName, "name", "n", "", "name of deployment to be created (if blank, generate UUID)")
cmdCreate.Flags().StringVarP(&flags.Platform, "platform", "p", "", "k8s | dockeree | none | k3s | ocp4 | eks | gke | aks | nomad (default "+defaults.Platform+")")
cmdCreate.Flags().StringVarP(&flags.Clusters, "clusters", "c", "", "number of clusters to be deployed (default "+defaults.Clusters+")")
cmdCreate.Flags().StringVarP(&flags.Nodes, "nodes", "N", "", "number of nodes to be deployed in each cluster (default "+defaults.Nodes+")")
cmdCreate.Flags().StringVarP(&flags.K8s_Version, "k8s_version", "k", "", "Kubernetes version to be deployed (default "+defaults.K8s_Version+")")
cmdCreate.Flags().StringVarP(&flags.Px_Version, "px_version", "P", "", "Portworx version to be deployed (default "+defaults.Px_Version+")")
cmdCreate.Flags().StringVarP(&flags.Stop_After, "stop_after", "s", "", "Stop instances after this many hours (default "+defaults.Stop_After+")")
cmdCreate.Flags().StringVarP(&flags.Aws_Type, "aws_type", "", "", "AWS type for each node (default "+defaults.Aws_Type+")")
cmdCreate.Flags().StringVarP(&flags.Aws_Ebs, "aws_ebs", "", "", "space-separated list of EBS volumes to be attached to worker nodes, eg \"gp2:20 standard:30\" (default "+defaults.Aws_Ebs+")")
cmdCreate.Flags().StringVarP(&flags.Aws_Access_Key_Id, "aws_access_key_id", "", "", "your AWS API access key id (default \""+defaults.Aws_Access_Key_Id+"\")")
cmdCreate.Flags().StringVarP(&flags.Aws_Secret_Access_Key, "aws_secret_access_key", "", "", "your AWS API secret access key (default \""+defaults.Aws_Secret_Access_Key+"\")")
cmdCreate.Flags().StringVarP(&flags.Tags, "tags", "", "", "comma-separated list of tags to be applies to cloud nodes, eg \"Owner=Bob,Purpose=Demo\"")
cmdCreate.Flags().StringVarP(&flags.Gcp_Type, "gcp_type", "", "", "GCP type for each node (default "+defaults.Gcp_Type+")")
cmdCreate.Flags().StringVarP(&flags.Gcp_Project, "gcp_project", "", "", "GCP Project")
cmdCreate.Flags().StringVarP(&flags.Gcp_Disks, "gcp_disks", "", "", "space-separated list of EBS volumes to be attached to worker nodes, eg \"pd-standard:20 pd-ssd:30\" (default "+defaults.Gcp_Disks+")")
cmdCreate.Flags().StringVarP(&flags.Gcp_Zone, "gcp_zone", "", defaults.Gcp_Zone, "GCP zone (a, b or c)")
cmdCreate.Flags().StringVarP(&flags.Aks_Version, "aks_version", "", "", "AKS Version (default "+defaults.Aks_Version+")")
cmdCreate.Flags().StringVarP(&flags.Eks_Version, "eks_version", "", "", "EKS Version (default "+defaults.Eks_Version+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Type, "azure_type", "", "", "Azure type for each node (default "+defaults.Azure_Type+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Client_Secret, "azure_client_secret", "", "", "Azure Client Secret (default "+defaults.Azure_Client_Secret+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Client_Id, "azure_client_id", "", "", "Azure client ID (default "+defaults.Azure_Client_Id+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Tenant_Id, "azure_tenant_id", "", "", "Azure tenant ID (default "+defaults.Azure_Tenant_Id+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Subscription_Id, "azure_subscription_id", "", "", "Azure subscription ID (default "+defaults.Azure_Subscription_Id+")")
cmdCreate.Flags().StringVarP(&flags.Azure_Disks, "azure_disks", "", "", "space-separated list of Azure disks to be attached to worker nodes, eg \"Standard_LRS:20 Premium_LRS:30\" (default "+defaults.Azure_Disks+")")
cmdCreate.Flags().StringVarP(&createTemplate, "template", "t", "", "name of template to be deployed")
cmdCreate.Flags().StringVarP(&createRegion, "region", "r", "", "AWS, GCP or Azure region (default "+defaults.Aws_Region+", "+defaults.Gcp_Region+" or "+defaults.Azure_Region+")")
cmdCreate.Flags().StringVarP(&flags.Cloud, "cloud", "C", "", "aws | gcp | azure | vsphere (default "+defaults.Cloud+")")
cmdCreate.Flags().StringVarP(&flags.Ssh_Pub_Key, "ssh_pub_key", "", "", "ssh public key which will be added for root access on each node")
cmdCreate.Flags().BoolVarP(&flags.Run_Predelete, "predelete", "", false, "run predelete scripts on destruction (true/false)")
cmdCreate.Flags().StringVarP(&createEnv, "env", "e", "", "Comma-separated list of environment variables to be passed, for example foo=bar,abc=123")
cmdCreate.Flags().BoolVarP(&flags.DryRun, "dry_run", "d", false, "dry-run, create local files only. Works only on aws / azure")
cmdCreate.Flags().BoolVarP(&flags.Lock, "lock", "", false, "protect deployment from deletion. run px-deploy unlock -n ... before deletion")
cmdDestroy.Flags().BoolVarP(&destroyAll, "all", "a", false, "destroy all deployments")
cmdDestroy.Flags().BoolVarP(&destroyClear, "clear", "c", false, "destroy local deployment files (use with caution!)")
cmdDestroy.Flags().BoolVarP(&destroyForce, "force", "f", false, "destroy even if predelete script exec fails")
cmdDestroy.Flags().StringVarP(&destroyName, "name", "n", "", "name of deployment to be destroyed")
cmdConnect.Flags().StringVarP(&connectName, "name", "n", "", "name of deployment to connect to")
cmdConnect.MarkFlagRequired("name")
cmdKubeconfig.Flags().StringVarP(&kubeconfigName, "name", "n", "", "name of deployment to connect to")
cmdKubeconfig.MarkFlagRequired("name")
cmdStatus.Flags().StringVarP(&statusName, "name", "n", "", "name of deployment")
cmdStatus.MarkFlagRequired("name")
cmdTesting.Flags().StringVarP(&testingName, "name", "n", "", "name of test run")
cmdTesting.MarkFlagRequired("name")
cmdTesting.Flags().StringVarP(&testingTemplate, "template", "t", "", "name of template to test")
cmdTesting.MarkFlagRequired("template")
cmdUnlock.Flags().StringVarP(&statusName, "name", "n", "", "name of deployment")
cmdUnlock.MarkFlagRequired("name")
cmdVsphereCheckTemplateVersion.Flags().StringVarP(&statusName, "name", "n", "", "name of deployment")
cmdVsphereCheckTemplateVersion.MarkFlagRequired("name")
cmdHistory.Flags().StringVarP(&historyNumber, "number", "n", "", "deployment ID")
rootCmd.AddCommand(cmdCreate, cmdDestroy, cmdConnect, cmdTesting, cmdKubeconfig, cmdList, cmdTemplates, cmdStatus, cmdCompletion, cmdVsphereInit, cmdVsphereCheckTemplateVersion, cmdVersion, cmdHistory, cmdUnlock)
rootCmd.Execute()
}
func validate_config(config *Config) []string {
var errormsg []string
if config.Cloud != "aws" && config.Cloud != "gcp" && config.Cloud != "azure" && config.Cloud != "vsphere" {
errormsg = append(errormsg, "Cloud must be 'aws', 'gcp', 'azure' or 'vsphere' (not '"+config.Cloud+"')")
}
// check parameter validity for each cloud
switch config.Cloud {
case "aws":
checkvar := []string{"aws_access_key_id", "aws_secret_access_key"}
emptyVars := isEmpty(config.Aws_Access_Key_Id, config.Aws_Secret_Access_Key)
if len(emptyVars) > 0 {
for _, i := range emptyVars {
errormsg = append(errormsg, fmt.Sprintf("please set %s in defaults.yml", checkvar[i]))
}
}
if !regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`).MatchString(config.Aws_Region) {
errormsg = append(errormsg, "Invalid region '"+config.Aws_Region+"'")
}
if !regexp.MustCompile(`^[0-9a-z\.]+$`).MatchString(config.Aws_Type) {
errormsg = append(errormsg, "Invalid AWS type '"+config.Aws_Type+"'")
}
if !regexp.MustCompile(`^[0-9a-z\ :]+$`).MatchString(config.Aws_Ebs) {
errormsg = append(errormsg, "Invalid AWS EBS volumes '"+config.Aws_Ebs+"'")
}
if !regexp.MustCompile(`^[0-9\.]+$`).MatchString(config.Eks_Version) {
errormsg = append(errormsg, "Invalid EKS version '"+config.Eks_Version+"'")
}
case "gcp":
checkvar := []string{"gcp_project"}
emptyVars := isEmpty(config.Gcp_Project)
if len(emptyVars) > 0 {
for _, i := range emptyVars {
errormsg = append(errormsg, fmt.Sprintf("please set %s in defaults.yml\n", checkvar[i]))
}
}
if config.Gcp_Project == "" {
errormsg = append(errormsg, "Please set gcp_project in defaults.yml")
}
if _, err := os.Stat("/px-deploy/.px-deploy/gcp.json"); os.IsNotExist(err) {
errormsg = append(errormsg, "~/.px-deploy/gcp.json not found. refer to readme.md how to create it")
}
if !regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`).MatchString(config.Gcp_Region) {
errormsg = append(errormsg, "Invalid region '"+config.Gcp_Region+"'")
}
if !regexp.MustCompile(`^[0-9a-z\-]+$`).MatchString(config.Gcp_Type) {
errormsg = append(errormsg, "Invalid GCP type '"+config.Gcp_Type+"'")
}
if !regexp.MustCompile(`^[0-9a-z\ :\-]+$`).MatchString(config.Gcp_Disks) {
errormsg = append(errormsg, "Invalid GCP disks '"+config.Gcp_Disks+"'")
}
if config.Gcp_Zone != "a" && config.Gcp_Zone != "b" && config.Gcp_Zone != "c" {
errormsg = append(errormsg, "Invalid GCP zone '"+config.Gcp_Zone+"'")
}
if !regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+`).MatchString(config.Gke_Version) {
errormsg = append(errormsg, "Invalid GKE version '"+config.Gke_Version+"'")
}
case "azure":
checkvar := []string{"azure_client_id", "azure_client_secret", "azure_tenant_id", "azure_subscription_id"}
emptyVars := isEmpty(config.Azure_Client_Id, config.Azure_Client_Secret, config.Azure_Tenant_Id, config.Azure_Subscription_Id)
if len(emptyVars) > 0 {
for _, i := range emptyVars {
errormsg = append(errormsg, fmt.Sprintf("please set %s in defaults.yml ", checkvar[i]))
}
}
if !regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`).MatchString(config.Azure_Region) {
errormsg = append(errormsg, "Invalid region '"+config.Azure_Region+"'")
}
if !regexp.MustCompile(`^[0-9\.]+$`).MatchString(config.Aks_Version) {
errormsg = append(errormsg, "Invalid AKS version '"+config.Aks_Version+"'")
}
if !regexp.MustCompile(`^[0-9a-zA-Z\-\_]+$`).MatchString(config.Azure_Type) {
errormsg = append(errormsg, "Invalid Azure type '"+config.Azure_Type+"'")
}
if !regexp.MustCompile(`^[0-9a-zA-Z\ \_:]+$`).MatchString(config.Azure_Disks) {
errormsg = append(errormsg, "Invalid Azure disks '"+config.Azure_Disks+"'")
}
case "vsphere":
checkvar := []string{"vsphere_compute_resource", "vsphere_datacenter", "vsphere_datastore", "vsphere_host", "vsphere_network", "vsphere_resource_pool", "vsphere_template", "vsphere_user", "vsphere_password", "vsphere_repo"}
emptyVars := isEmpty(config.Vsphere_Compute_Resource, config.Vsphere_Datacenter, config.Vsphere_Datastore, config.Vsphere_Host, config.Vsphere_Network, config.Vsphere_Resource_Pool, config.Vsphere_Template, config.Vsphere_User, config.Vsphere_Password, config.Vsphere_Repo)
if len(emptyVars) > 0 {
for _, i := range emptyVars {
errormsg = append(errormsg, fmt.Sprintf("please set %s in defaults.yml ", checkvar[i]))
}
}
config.Vsphere_Template = strings.TrimLeft(config.Vsphere_Template, "/")
config.Vsphere_Folder = strings.TrimLeft(config.Vsphere_Folder, "/")
config.Vsphere_Folder = strings.TrimRight(config.Vsphere_Folder, "/")
}
if config.Platform != "k8s" && config.Platform != "k3s" && config.Platform != "none" && config.Platform != "dockeree" && config.Platform != "ocp4" && config.Platform != "eks" && config.Platform != "gke" && config.Platform != "aks" && config.Platform != "nomad" {
errormsg = append(errormsg, "Invalid platform '"+config.Platform+"'")
}
if !regexp.MustCompile(`^[0-9]+$`).MatchString(config.Clusters) {
errormsg = append(errormsg, "Invalid number of clusters")
}
if !regexp.MustCompile(`^[0-9]+$`).MatchString(config.Nodes) {
errormsg = append(errormsg, "Invalid number of nodes")
}
if !regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`).MatchString(config.K8s_Version) {
errormsg = append(errormsg, "Invalid Kubernetes version '"+config.K8s_Version+"'")
}
if !regexp.MustCompile(`^[0-9\.]+$`).MatchString(config.Px_Version) {
errormsg = append(errormsg, "Invalid Portworx version '"+config.Px_Version+"'")
}
if !regexp.MustCompile(`^[0-9]+$`).MatchString(config.Stop_After) {
errormsg = append(errormsg, "Invalid number of hours")
}
if !regexp.MustCompile(`^((([\p{L}\p{Z}\p{N}_.:+\-]*)=([\p{L}\p{Z}\p{N}_.:+\-]*),)*(([\p{L}\p{Z}\p{N}_.:+\-]*)=([\p{L}\p{Z}\p{N}_.:+\-]*)){1})*$`).MatchString(config.Tags) {
errormsg = append(errormsg, "Invalid tags '"+config.Tags+"'")
}
for _, c := range config.Cluster {
for _, s := range c.Scripts {
if _, err := os.Stat("scripts/" + s); os.IsNotExist(err) {
errormsg = append(errormsg, "Script '"+s+"' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+s)
err := cmd.Run()
if err != nil {
errormsg = append(errormsg, "Script '"+s+"' is not valid Bash")
}
}
}
for _, s := range config.Scripts {
if _, err := os.Stat("scripts/" + s); os.IsNotExist(err) {
errormsg = append(errormsg, "Script '"+s+"' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+s)
err := cmd.Run()
if err != nil {
errormsg = append(errormsg, "Script '"+s+"' is not valid Bash")
}
}
if config.Post_Script != "" {
if _, err := os.Stat("scripts/" + config.Post_Script); os.IsNotExist(err) {
errormsg = append(errormsg, "Postscript '"+config.Post_Script+"' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+config.Post_Script)
err := cmd.Run()
if err != nil {
errormsg = append(errormsg, "Postscript '"+config.Post_Script+"' is not valid Bash")
}
}
if config.Platform == "ocp4" {
checkvar := []string{"ocp4_domain", "ocp4_pull_secret"}
emptyVars := isEmpty(config.Ocp4_Domain, config.Ocp4_Pull_Secret)
if len(emptyVars) > 0 {
for _, i := range emptyVars {
errormsg = append(errormsg, "please set \"%s\" in defaults.yml", checkvar[i])
}
}
}
if config.Platform == "eks" && !(config.Cloud == "aws") {
errormsg = append(errormsg, "EKS only makes sense with AWS (not "+config.Cloud+")")
}
if config.Platform == "ocp4" && config.Cloud != "aws" {
errormsg = append(errormsg, "Openshift 4 only supported on AWS (not "+config.Cloud+")")
}
if config.Platform == "gke" && config.Cloud != "gcp" {
errormsg = append(errormsg, "GKE only makes sense with GCP (not "+config.Cloud+")")
}
if config.Platform == "aks" && config.Cloud != "azure" {
errormsg = append(errormsg, "AKS only makes sense with Azure (not "+config.Cloud+")")
}
return errormsg
}
// merge defaults.yml / template settings / flag parameters and create deployment.yml file
func prepare_deployment(config *Config, flags *Config, createName string, createEnv string, createTemplate string, createRegion string) string {
var env_template map[string]string
env := config.Env
if createTemplate != "" {
config.Template = createTemplate
config_template := parse_yaml("templates/" + createTemplate + ".yml")
env_template = config_template.Env
mergo.MergeWithOverwrite(config, config_template)
mergo.MergeWithOverwrite(&env, env_template)
}
if createEnv != "" {
env_flags := make(map[string]string)
for _, kv := range strings.Split(createEnv, ",") {
s := strings.Split(kv, "=")
env_flags[s[0]] = s[1]
}
mergo.MergeWithOverwrite(&flags.Env, env_flags)
}
config.Env = env
mergo.MergeWithOverwrite(config, flags)
configerr := validate_config(config)
if configerr != nil {
var validate_error []byte
validate_error = append(validate_error, fmt.Sprint(Red)...)
validate_error = append(validate_error, fmt.Sprintf("Found %v errors in config \n", len(configerr))...)
for elem := range configerr {
validate_error = append(validate_error, fmt.Sprintln(configerr[elem])...)
}
validate_error = append(validate_error, fmt.Sprint(Reset)...)
return string(validate_error)
}
if createName != "" {
if !regexp.MustCompile(`^[a-z0-9_\-\.]+$`).MatchString(createName) {
return fmt.Sprintf("Invalid deployment name %s\n", createName)
}
if _, err := os.Stat("deployments/" + createName + ".yml"); !os.IsNotExist(err) {
return fmt.Sprintf("%sDeployment '%s' already exists%s\n Please delete it by running 'px-deploy destroy -n %s' \n If this fails, remove cloud resources manually and run 'px-deploy destroy --clear -n %s'\n", Red, createName, Reset, createName, createName)
}
} else {
createName = uuid.New().String()
}
config.Name = createName
if createRegion != "" {
switch config.Cloud {
case "aws":
config.Aws_Region = createRegion
case "gcp":
config.Gcp_Region = createRegion
case "azure":
config.Azure_Region = createRegion
default:
return fmt.Sprintf("setting cloud region not supported on %s\n", config.Cloud)
}
}
// remove AWS credentials from deployment specific yml as we should not rely on it later
cleanConfig := *config
if cleanConfig.Cloud == "aws" {
cleanConfig.Aws_Access_Key_Id = ""
cleanConfig.Aws_Secret_Access_Key = ""
}
y, _ := yaml.Marshal(cleanConfig)
log("[ " + strings.Join(os.Args[1:], " ") + " ] " + base64.StdEncoding.EncodeToString(y))
err := os.WriteFile("deployments/"+createName+".yml", y, 0644)
if err != nil {
return (err.Error())
}
return ""
}
func get_deployment_status(config *Config, cluster int, c chan Deployment_Status_Return) {
defer wg.Done()
var ip string
var Nodes int
var returnvalue string
if (config.Platform == "ocp4") || (config.Platform == "eks") || (config.Platform == "aks") || (config.Platform == "gke") {
Nodes = 0
} else {
Nodes, _ = strconv.Atoi(config.Nodes)
//check for cluster specific node # overrides
for _, cl_entry := range config.Cluster {
if (cl_entry.Id == cluster) && (cl_entry.Nodes != "") {
Nodes, _ = strconv.Atoi(cl_entry.Nodes)
}
}
}
switch config.Cloud {
case "aws":
ip = aws_get_node_ip(config.Name, fmt.Sprintf("master-%v-1", cluster))
case "azure":
ip = azure_get_node_ip(config.Name, fmt.Sprintf("master-%v-1", cluster))
case "gcp":
ip = gcp_get_node_ip(config.Name, fmt.Sprintf("%v-master-%v-1", config.Name, cluster))
case "vsphere":
ip = vsphere_get_node_ip(config, fmt.Sprintf("%v-master-%v", config.Name, cluster))
}
// get content of node tracking file (-> each node will add its entry when finished cloud-init/vagrant scripts)
cmd := exec.Command("ssh", "-q", "-oStrictHostKeyChecking=no", "-i", "keys/id_rsa."+config.Cloud+"."+config.Name, "root@"+ip, "cat /var/log/px-deploy/completed/tracking")
out, err := cmd.CombinedOutput()
if err != nil {
returnvalue = fmt.Sprintf("Error get status of cluster %v\n Message: %v\n", cluster, err.Error())
//c <- returnvalue
} else {
scanner := bufio.NewScanner(strings.NewReader(string(out)))
ready_nodes := make(map[string]string)
for scanner.Scan() {
entry := strings.Fields(scanner.Text())
ready_nodes[entry[0]] = entry[1]
}
if ready_nodes[fmt.Sprintf("master-%v", cluster)] != "" {
returnvalue = fmt.Sprintf("%vReady\tmaster-%v \t %v\n", returnvalue, cluster, ip)
} else {
returnvalue = fmt.Sprintf("%vNotReady\tmaster-%v \t (%v)\n", returnvalue, cluster, ip)
}
if config.Platform == "ocp4" {
if ready_nodes["url"] != "" {
returnvalue = fmt.Sprintf("%v URL: %v \n", returnvalue, ready_nodes["url"])
} else {
returnvalue = fmt.Sprintf("%v OCP4 URL not yet available\n", returnvalue)
}
if ready_nodes["cred"] != "" {
returnvalue = fmt.Sprintf("%v Credentials: kubeadmin / %v \n", returnvalue, ready_nodes["cred"])
} else {
returnvalue = fmt.Sprintf("%v OCP4 credentials not yet available\n", returnvalue)
}
}
for n := 1; n <= Nodes; n++ {
if ready_nodes[fmt.Sprintf("node-%v-%v", cluster, n)] != "" {
returnvalue = fmt.Sprintf("%vReady\t node-%v-%v\n", returnvalue, cluster, n)
} else {
returnvalue = fmt.Sprintf("%vNotReady\t node-%v-%v\n", returnvalue, cluster, n)
}
}
}
c <- Deployment_Status_Return{cluster, returnvalue}
}
func create_deployment(config Config) bool {
var err error
fmt.Println(White + "Provisioning infrastructure..." + Reset)
switch config.Cloud {
case "aws":
{
// create directory for deployment and copy terraform scripts
err = os.Mkdir("/px-deploy/.px-deploy/tf-deployments/"+config.Name, 0755)
if err != nil {
fmt.Println(err.Error())
return false
}
//maybe there is a better way to copy templates to working dir ?
exec.Command("cp", "-a", `/px-deploy/terraform/aws/main.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/variables.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/cloud-init.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/aws-returns.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// also copy terraform modules
//exec.Command("cp", "-a", `/px-deploy/terraform/aws/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// creating symlink for .terraform as performance on mac significantly improves when not on bind mount issue #397
exec.Command("ln", "-s", `/px-deploy/terraform/aws/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name+`/.terraform`).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/.terraform.lock.hcl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
switch config.Platform {
case "ocp4":
{
exec.Command("cp", "-a", `/px-deploy/terraform/aws/ocp4/ocp4.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/ocp4/ocp4-install-config.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
}
case "eks":
{
exec.Command("cp", "-a", `/px-deploy/terraform/aws/eks/eks.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/aws/eks/eks_run_everywhere.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
}
}
write_nodescripts(config)
write_tf_file(config.Name, ".tfvars", aws_create_variables(&config))
tf_error := run_terraform_apply(&config)
if tf_error != "" {
fmt.Printf("%s\n", tf_error)
return false
}
aws_show_iamkey_age(&config)
}
case "gcp":
{
// create directory for deployment and copy terraform scripts
err = os.Mkdir("/px-deploy/.px-deploy/tf-deployments/"+config.Name, 0755)
if err != nil {
fmt.Println(err.Error())
return false
}
//maybe there is a better way to copy templates to working dir ?
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/main.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/variables.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/startup-script.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/gcp-returns.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// also copy terraform modules
//exec.Command("cp", "-a", `/px-deploy/terraform/gcp/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// creating symlink for .terraform as performance on mac significantly improves when not on bind mount issue #397
exec.Command("ln", "-s", `/px-deploy/terraform/gcp/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name+`/.terraform`).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/.terraform.lock.hcl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
switch config.Platform {
case "gke":
{
exec.Command("cp", "-a", `/px-deploy/terraform/gcp/gke/gke.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
}
}
write_nodescripts(config)
write_tf_file(config.Name, ".tfvars", gcp_create_variables(&config))
tf_error := run_terraform_apply(&config)
if tf_error != "" {
fmt.Printf("%s\n", tf_error)
return false
}
}
case "azure":
{
// create directory for deployment and copy terraform scripts
err = os.Mkdir("/px-deploy/.px-deploy/tf-deployments/"+config.Name, 0755)
if err != nil {
fmt.Println(err.Error())
return false
}
//maybe there is a better way to copy templates to working dir ?
exec.Command("cp", "-a", `/px-deploy/terraform/azure/main.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/azure/variables.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/azure/cloud-init.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// also copy terraform modules
//exec.Command("cp", "-a", `/px-deploy/terraform/azure/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// creating symlink for .terraform as performance on mac significantly improves when not on bind mount issue #397
exec.Command("ln", "-s", `/px-deploy/terraform/azure/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name+`/.terraform`).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/azure/.terraform.lock.hcl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
switch config.Platform {
case "aks":
{
exec.Command("cp", "-a", `/px-deploy/terraform/azure/aks/aks.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
//exec.Command("cp", "-a", `/px-deploy/terraform/azure/aks/aks_run_everywhere.tpl`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
}
}
write_nodescripts(config)
write_tf_file(config.Name, ".tfvars", azure_create_variables(&config))
tf_error := run_terraform_apply(&config)
if tf_error != "" {
fmt.Printf("%s\n", tf_error)
return false
}
}
case "vsphere":
{
// create directory for deployment and copy terraform scripts
err = os.Mkdir("/px-deploy/.px-deploy/tf-deployments/"+config.Name, 0755)
if err != nil {
fmt.Println(err.Error())
return false
}
//maybe there is a better way to copy templates to working dir ?
exec.Command("cp", "-a", `/px-deploy/terraform/vsphere/main.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/vsphere/variables.tf`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/vsphere/cloud-init.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/vsphere/metadata.tpl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// also copy terraform modules
//exec.Command("cp", "-a", `/px-deploy/terraform/gcp/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
// creating symlink for .terraform as performance on mac significantly improves when not on bind mount issue #397
exec.Command("ln", "-s", `/px-deploy/terraform/vsphere/.terraform`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name+`/.terraform`).Run()
exec.Command("cp", "-a", `/px-deploy/terraform/vsphere/.terraform.lock.hcl`, `/px-deploy/.px-deploy/tf-deployments/`+config.Name).Run()
write_nodescripts(config)
write_tf_file(config.Name, ".tfvars", vsphere_create_variables(&config))
tf_error := run_terraform_apply(&config)
if tf_error != "" {
fmt.Printf("%s\n", tf_error)
return false
}
vsphere_check_templateversion(config.Name)
}
default:
fmt.Println("Invalid cloud '" + config.Cloud + "'")
return false
}
if config.Lock {
lockfile, err := os.OpenFile("tf-deployments/"+config.Name+"/"+config.Name+".lock", os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
panic(err.Error())
}
lockfile.Close()
}
return true
}
func run_terraform_apply(config *Config) string {
var cloud_auth []string
fmt.Println(White + "running terraform PLAN" + Reset)
cmd := exec.Command("terraform", "-chdir=/px-deploy/.px-deploy/tf-deployments/"+config.Name, "plan", "-input=false", "-parallelism=50", "-out=tfplan", "-var-file", ".tfvars")
cmd.Stderr = os.Stderr
switch config.Cloud {
case "aws":
cloud_auth = append(cloud_auth, fmt.Sprintf("AWS_ACCESS_KEY_ID=%s", config.Aws_Access_Key_Id))
cloud_auth = append(cloud_auth, fmt.Sprintf("AWS_SECRET_ACCESS_KEY=%s", config.Aws_Secret_Access_Key))
}
cmd.Env = append(cmd.Env, cloud_auth...)
err := cmd.Run()
if err != nil {
fmt.Println(Yellow + "ERROR: terraform plan failed. Check validity of terraform scripts" + Reset)
return err.Error()
} else {
if config.DryRun {
fmt.Printf("Dry run only. No deployment on target cloud. Run 'px-deploy destroy -n %s' to remove local files\n", config.Name)
return ""
}
fmt.Println(White + "running terraform APPLY" + Reset)
cmd := exec.Command("terraform", "-chdir=/px-deploy/.px-deploy/tf-deployments/"+config.Name, "apply", "-input=false", "-parallelism=50", "-auto-approve", "tfplan")
cmd.Stdout = os.Stdout