forked from PureStorage-OpenConnect/px-deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpx-deploy.go
1398 lines (1301 loc) · 59.2 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 (
"fmt"
"io"
"io/ioutil"
"bufio"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"unicode/utf8"
"net/http"
"encoding/base64"
"reflect"
"github.com/go-yaml/yaml"
"github.com/google/uuid"
"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
Auto_Destroy string
Quiet string
Dry_Run string
Aws_Type string
Aws_Ebs string
Aws_Tags string
Gcp_Type string
Gcp_Disks string
Gcp_Zone string
Azure_Type string
Azure_Disks 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_Folder string
Vsphere_Disks string
Vsphere_Network string
Vsphere_Memory string
Vsphere_Cpu 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"`
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"`
}
type Config_Cluster struct {
Id int
Scripts []string
Aws_Type string
}
var Reset = "\033[0m"
var White = "\033[97m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
func main() {
var createName, createPlatform, createClusters, createNodes, createK8sVer, createPxVer, createStopAfter, createAwsType, createAwsEbs, createAwsTags, createGcpType, createGcpDisks, createGcpZone, createAzureType, createAzureDisks, createTemplate, createRegion, createCloud, createEnv, connectName, kubeconfigName, destroyName, statusName, historyNumber string
var createQuiet, createDryRun, destroyAll bool
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) {
version_current := get_version_current()
version_latest := get_version_latest()
if version_latest == "" {
fmt.Println(Yellow + "Current version is " + version_current + ", cannot determine latest version")
} else {
if version_current != version_latest {
fmt.Println(Yellow + "Current version is " + version_current + ", latest version is " + version_latest)
} else {
fmt.Println(Green + "Current version is " + version_current + " (latest)")
}
}
fmt.Print(Reset)
if len(args) > 0 {
die("Invalid arguments")
}
config := parse_yaml("defaults.yml")
env := config.Env
var env_template map[string]string
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 createName != "" {
if !regexp.MustCompile(`^[a-z0-9_\-\.]+$`).MatchString(createName) {
die("Invalid deployment name '" + createName + "'")
}
if _, err := os.Stat("deployments/" + createName + ".yml"); !os.IsNotExist(err) {
die("Deployment '" + createName + "' already exists")
}
} else {
createName = uuid.New().String()
}
config.Name = createName
if createCloud != "" {
if createCloud != "aws" && createCloud != "awstf" && createCloud != "gcp" && createCloud != "azure" && createCloud != "vsphere" {
die("Cloud must be 'awstf', 'aws', 'gcp', 'azure' or 'vsphere' (not '" + createCloud + "')")
}
config.Cloud = createCloud
}
if createRegion != "" {
if !regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`).MatchString(createRegion) {
die("Invalid region '" + createRegion + "'")
}
switch config.Cloud {
case "aws":
config.Aws_Region = createRegion
case "awstf":
config.Aws_Region = createRegion
case "gcp":
config.Gcp_Region = createRegion
case "azure":
config.Azure_Region = createRegion
default:
die("Bad cloud")
}
}
if createPlatform != "" {
if createPlatform != "k8s" && createPlatform != "k3s" && createPlatform != "none" && createPlatform != "dockeree" && createPlatform != "ocp3" && createPlatform != "ocp3c" && createPlatform != "ocp4" && createPlatform != "eks" && createPlatform != "gke" && createPlatform != "aks" && createPlatform != "nomad" {
die("Invalid platform '" + createPlatform + "'")
}
config.Platform = createPlatform
}
if createClusters != "" {
if !regexp.MustCompile(`^[0-9]+$`).MatchString(createClusters) {
die("Invalid number of clusters")
}
config.Clusters = createClusters
}
if createNodes != "" {
if !regexp.MustCompile(`^[0-9]+$`).MatchString(createNodes) {
die("Invalid number of nodes")
}
config.Nodes = createNodes
}
if createK8sVer != "" {
if !regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`).MatchString(createK8sVer) {
die("Invalid Kubernetes version '" + createK8sVer + "'")
}
config.K8s_Version = createK8sVer
}
if createPxVer != "" {
if !regexp.MustCompile(`^[0-9\.]+$`).MatchString(createPxVer) {
die("Invalid Portworx version '" + createPxVer + "'")
}
config.Px_Version = createPxVer
}
if createStopAfter != "" {
if !regexp.MustCompile(`^[0-9]+$`).MatchString(createStopAfter) {
die("Invalid number of hours")
}
config.Stop_After = createStopAfter
}
if createEnv != "" {
env_cli := make(map[string]string)
for _, kv := range strings.Split(createEnv, ",") {
s := strings.Split(kv, "=")
env_cli[s[0]] = s[1]
}
mergo.MergeWithOverwrite(&env, env_cli)
}
config.Env = env
if createQuiet {
config.Quiet = "true"
}
if createDryRun {
config.Dry_Run = "true"
}
if createAwsType != "" {
if !regexp.MustCompile(`^[0-9a-z\.]+$`).MatchString(createAwsType) {
die("Invalid AWS type '" + createAwsType + "'")
}
config.Aws_Type = createAwsType
}
if createAwsEbs != "" {
if !regexp.MustCompile(`^[0-9a-z\ :]+$`).MatchString(createAwsEbs) {
die("Invalid AWS EBS volumes '" + createAwsEbs + "'")
}
config.Aws_Ebs = createAwsEbs
}
if createAwsTags != "" {
if !regexp.MustCompile(`^[0-9a-zA-Z,=\ ]+$`).MatchString(createAwsTags) {
die("Invalid AWS tags '" + createAwsTags + "'")
}
config.Aws_Tags = createAwsTags
}
if createGcpType != "" {
if !regexp.MustCompile(`^[0-9a-z\-]+$`).MatchString(createGcpType) {
die("Invalid GCP type '" + createGcpType + "'")
}
config.Gcp_Type = createGcpType
}
if createGcpDisks != "" {
if !regexp.MustCompile(`^[0-9a-z\ :\-]+$`).MatchString(createGcpDisks) {
die("Invalid GCP disks '" + createGcpDisks + "'")
}
config.Gcp_Disks = createGcpDisks
}
if createGcpZone != "" {
if createGcpZone != "a" && createGcpZone != "b" && createGcpZone != "c" {
die("Invalid GCP zone '" + createGcpZone + "'")
}
config.Gcp_Zone = createGcpZone
}
if createAzureType != "" {
if !regexp.MustCompile(`^[0-9a-z\-]+$`).MatchString(createAzureType) {
die("Invalid Azure type '" + createAzureType + "'")
}
config.Azure_Type = createAzureType
}
if createAzureDisks != "" {
if !regexp.MustCompile(`^[0-9 ]+$`).MatchString(createAzureDisks) {
die("Invalid Azure disks '" + createAzureDisks + "'")
}
config.Azure_Disks = createAzureDisks
}
for _, c := range config.Cluster {
for _, s := range c.Scripts {
if _, err := os.Stat("scripts/" + s); os.IsNotExist(err) {
die("Script '" + s + "' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+s)
err := cmd.Run()
if err != nil {
die("Script '" + s + "' is not valid Bash")
}
}
}
for _, s := range config.Scripts {
if _, err := os.Stat("scripts/" + s); os.IsNotExist(err) {
die("Script '" + s + "' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+s)
err := cmd.Run()
if err != nil {
die("Script '" + s + "' is not valid Bash")
}
}
if config.Post_Script != "" {
if _, err := os.Stat("scripts/" + config.Post_Script); os.IsNotExist(err) {
die("Postscript '" + config.Post_Script + "' does not exist")
}
cmd := exec.Command("bash", "-n", "scripts/"+config.Post_Script)
err := cmd.Run()
if err != nil {
die("Postscript '" + config.Post_Script + "' is not valid Bash")
}
}
// enable when ocp4/eks destroy is fixed for awstf
//if config.Platform == "ocp4" && !(config.Cloud == "aws" || config.Cloud == "awstf") { die("Openshift 4 only supported on AWS (not " + config.Cloud + ")") }
//if config.Platform == "eks" && !(config.Cloud == "aws" || config.Cloud == "awstf") { die("EKS only makes sense with AWS (not " + config.Cloud + ")") }
if config.Platform == "ocp4" && config.Cloud != "aws" { die("Openshift 4 only supported on AWS (not " + config.Cloud + ")") }
if config.Platform == "eks" && config.Cloud != "aws" { die("EKS only makes sense with AWS (not " + config.Cloud + ")") }
if config.Platform == "gke" && config.Cloud != "gcp" { die("GKE only makes sense with GCP (not " + config.Cloud + ")") }
if config.Platform == "aks" && config.Cloud != "azure" { die("AKS only makes sense with Azure (not " + config.Cloud + ")") }
y, _ := yaml.Marshal(config)
log("[ "+ strings.Join(os.Args[1:], " ") + " ] " + base64.StdEncoding.EncodeToString(y))
if config.Dry_Run == "true" {
fmt.Println(string(y))
die("Dry-run only")
}
err := ioutil.WriteFile("deployments/"+createName+".yml", y, 0644)
if err != nil {
die(err.Error())
}
if create_deployment(config) != 0 {
destroy_deployment(config.Name)
die("Aborted")
}
os.Chdir("/px-deploy/vagrant")
os.Setenv("deployment", config.Name)
// when using awstf everything should be up and running. other clouds now run vagrant
if config.Cloud != "awstf" {
var provider string
switch config.Cloud {
case "aws":
provider = "aws"
case "gcp":
provider = "google"
case "azure":
provider = "azure"
case "vsphere":
provider = "vsphere"
}
fmt.Println(White + "Provisioning VMs..." + Reset)
vcmd := exec.Command("sh", "-c", "vagrant up --provider " + provider + " 2>&1")
stdout, err := vcmd.StdoutPipe()
if err != nil {
die(err.Error())
}
if err := vcmd.Start(); err != nil {
die(err.Error())
}
reader := bufio.NewReader(stdout)
for {
data := make([]byte, 4<<20)
_, err := reader.Read(data)
if (config.Quiet != "true") {
fmt.Print(string(data))
}
if err == io.EOF {
break
}
}
if err := vcmd.Wait(); err != nil {
die(err.Error())
}
}
if config.Auto_Destroy == "true" {
destroy_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 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)
destroy_deployment(config.Name)
return nil
})
} else {
if destroyName == "" {
die("Must specify deployment to destroy")
}
destroy_deployment(destroyName)
}
},
}
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 = ioutil.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()
},
}
cmdStatus := &cobra.Command{
Use: "status name",
Short: "Lists master IPs in a deployment",
Long: "Lists master IPs in a deployment",
Run: func(cmd *cobra.Command, args []string) {
config := parse_yaml("deployments/" + statusName + ".yml")
ip := get_ip(statusName)
Clusters, _ := strconv.Atoi(config.Clusters)
Nodes, _ := strconv.Atoi(config.Nodes)
switch config.Cloud {
case "awstf":
{
// loop clusters and add master name/ip to tf var
for c := 1; c <= Clusters ; c++ {
ip = get_node_ip(statusName,fmt.Sprintf("master-%v",c))
// 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{
die (err.Error())
} 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",c)] != "" {
fmt.Printf("Ready\tmaster-%v \t %v\n",c, ip )
} else {
fmt.Printf("NotReady\tmaster-%v \t (%v)\n",c,ip)
}
for n := 1; n <= Nodes; n++ {
if ready_nodes[fmt.Sprintf("node-%v-%v",c,n)] != "" {
fmt.Printf("Ready\t node-%v-%v\n",c,n)
} else {
fmt.Printf("NotReady\t node-%v-%v\n",c,n)
}
}
}
}
}
default:
{
c := `
masters=$(grep master /etc/hosts | cut -f 2 -d " ")
for m in $masters; do
ip=$(sudo ssh -oStrictHostKeyChecking=no $m "curl http://ipinfo.io/ip" 2>/dev/null)
hostname=$(sudo ssh -oStrictHostKeyChecking=no $m "curl http://ipinfo.io/hostname" 2>/dev/null)
echo $m $ip $hostname
done`
syscall.Exec("/usr/bin/ssh", []string{"ssh", "-q", "-oStrictHostKeyChecking=no", "-i", "keys/id_rsa." + config.Cloud + "." + config.Name, "root@" + ip, c}, []string{})
}
}
},
}
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()
},
}
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(&createPlatform, "platform", "p", "", "k8s | dockeree | none | k3s | ocp3 | ocp3c | ocp4 | eks | gke | aks | nomad (default "+defaults.Platform+")")
cmdCreate.Flags().StringVarP(&createClusters, "clusters", "c", "", "number of clusters to be deployed (default "+defaults.Clusters+")")
cmdCreate.Flags().StringVarP(&createNodes, "nodes", "N", "", "number of nodes to be deployed in each cluster (default "+defaults.Nodes+")")
cmdCreate.Flags().StringVarP(&createK8sVer, "k8s_version", "k", "", "Kubernetes version to be deployed (default "+defaults.K8s_Version+")")
cmdCreate.Flags().StringVarP(&createPxVer, "px_version", "P", "", "Portworx version to be deployed (default "+defaults.Px_Version+")")
cmdCreate.Flags().StringVarP(&createStopAfter, "stop_after", "s", "", "Stop instances after this many hours (default "+defaults.Stop_After+")")
cmdCreate.Flags().StringVarP(&createAwsType, "aws_type", "", "", "AWS type for each node (default "+defaults.Aws_Type+")")
cmdCreate.Flags().StringVarP(&createAwsEbs, "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(&createAwsTags, "aws_tags", "", "", "comma-separated list of tags to be applies to AWS nodes, eg \"Owner=Bob,Purpose=Demo\"")
cmdCreate.Flags().StringVarP(&createGcpType, "gcp_type", "", "", "GCP type for each node (default "+defaults.Gcp_Type+")")
cmdCreate.Flags().StringVarP(&createGcpDisks, "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(&createGcpZone, "gcp_zone", "", defaults.Gcp_Zone, "GCP zone (a, b or c)")
cmdCreate.Flags().StringVarP(&createAzureType, "azure_type", "", "", "Azure type for each node (default "+defaults.Azure_Type+")")
cmdCreate.Flags().StringVarP(&createAzureDisks, "azure_disks", "", "", "space-separated list of Azure disks to be attached to worker nodes, eg \"20 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(&createCloud, "cloud", "C", "", "aws | gcp | azure | vsphere (default "+defaults.Cloud+")")
cmdCreate.Flags().StringVarP(&createEnv, "env", "e", "", "Comma-separated list of environment variables to be passed, for example foo=bar,abc=123")
cmdCreate.Flags().BoolVarP(&createQuiet, "quiet", "q", false, "hide provisioning output")
cmdCreate.Flags().BoolVarP(&createDryRun, "dry_run", "d", false, "dry-run, output yaml only")
cmdDestroy.Flags().BoolVarP(&destroyAll, "all", "a", false, "destroy all deployments")
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")
cmdHistory.Flags().StringVarP(&historyNumber, "number", "n", "", "deployment ID")
rootCmd.AddCommand(cmdCreate, cmdDestroy, cmdConnect, cmdKubeconfig, cmdList, cmdTemplates, cmdStatus, cmdCompletion, cmdVsphereInit, cmdVersion, cmdHistory)
rootCmd.Execute()
}
func create_deployment(config Config) int {
var output []byte
var err error
var errapply error
var pxduser string
var tf_node_scripts []string
var tf_master_scripts []string
var tf_variables []string
var tf_var_masters []string
var tf_var_nodes []string
var tf_common_master_script []byte
var tf_post_script []byte
var tf_node_script []byte
var tf_individual_node_script []byte
var tf_master_script []byte
var tf_cluster_aws_type string
var tf_env_script []byte
var tf_var_ebs_common []string
var tf_var_ebs []string
fmt.Println(White + "Provisioning infrastructure..." + Reset)
switch config.Cloud {
case "awstf":
{
// create directory for deployment and copy terraform scripts
err = os.Mkdir("/px-deploy/.px-deploy/tf-deployments/" + config.Name, 0755)
if err != nil {
die(err.Error())
}
//maybe there is a better way to copy templates to working dir ?
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/main.tf`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/variables.tf`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/cloud-init-master.tpl`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/cloud-init-node.tpl`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/aws-returns.tpl`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
// also copy terraform modules
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/.terraform`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
exec.Command("cp", "-a", `/px-deploy/.px-deploy/terraform/awstf/.terraform.lock.hcl`,`/px-deploy/.px-deploy/tf-deployments/`+ config.Name).Run()
// prepare ENV variables for node/master scripts
// to maintain compatibility, create a env variable of everything from the yml spec which is from type string
e := reflect.ValueOf(&config).Elem()
for i:=0; i < e.NumField(); i++ {
if e.Type().Field(i).Type.Name() == "string" {
tf_env_script = append(tf_env_script,"export "+strings.ToLower(strings.TrimSpace(e.Type().Field(i).Name))+"=\""+strings.ToLower(strings.TrimSpace(e.Field(i).Interface().(string)))+"\"\n"...)
}
}
// set env variables from env spec
for key,val := range config.Env {
tf_env_script = append(tf_env_script,"export "+key+"=\""+val+"\"\n"...)
}
err = os.WriteFile("/px-deploy/.px-deploy/tf-deployments/" + config.Name + "/env.sh", tf_env_script, 0666)
if err != nil {
die(err.Error())
}
// create EBS definitions
// split ebs definition by spaces and range the results
tf_var_ebs = append(tf_var_ebs,"node_ebs_devices ={")
ebs := strings.Fields(config.Aws_Ebs)
for i,val := range ebs {
// split by : and create common .tfvars entry for all nodes
entry := strings.Split(val,":")
tf_var_ebs_common = append(tf_var_ebs_common, " ebs_type = \""+entry[0]+"\"\n ebs_size = \""+entry[1]+"\"\n ebs_device_name = \"/dev/sd"+string(i+98)+"\"")
}
// other node ebs processing happens in cluster/node loop
subnet := "192.168."
// use aws vagrant scripts as awstf is just the tf implementation of aws
// prepare (single) cloud-init script for all nodes
tf_node_scripts = []string{"all-common",config.Platform+"-common",config.Platform+"-node"}
tf_node_script = append(tf_node_script,"#!/bin/bash\n"...)
tf_node_script = append(tf_node_script,"mkdir /var/log/px-deploy\n"...)
for _,filename := range tf_node_scripts {
content, err := ioutil.ReadFile("/px-deploy/vagrant/"+filename)
if err == nil {
tf_node_script = append(tf_node_script,"(\n"...)
tf_node_script = append(tf_node_script,"echo \"Started ($date)\"\n"...)
tf_node_script = append(tf_node_script,content...)
tf_node_script = append(tf_node_script,"echo \"Finished ($date)\"\n"...)
tf_node_script = append(tf_node_script,"\n) >&/var/log/px-deploy/"+filename+"\n"...)
}
}
// prepare common base script for all master nodes
// prepare common cloud-init script for all master nodes
tf_master_scripts = []string{"all-common",config.Platform+"-common","all-master",config.Platform+"-master"}
tf_common_master_script = append(tf_common_master_script,"#!/bin/bash\n"...)
tf_common_master_script = append(tf_common_master_script,"mkdir /var/log/px-deploy\n"...)
tf_common_master_script = append(tf_common_master_script,"mkdir /var/log/px-deploy/completed\n"...)
tf_common_master_script = append(tf_common_master_script,"touch /var/log/px-deploy/completed/tracking\n"...)
for _,filename := range tf_master_scripts {
content, err := ioutil.ReadFile("/px-deploy/vagrant/"+filename)
if err == nil {
tf_common_master_script = append(tf_common_master_script,"(\n"...)
tf_common_master_script = append(tf_common_master_script,"echo \"Started $(date)\"\n"...)
tf_common_master_script = append(tf_common_master_script,content...)
tf_common_master_script = append(tf_common_master_script,"echo \"Finished $(date)\"\n"...)
tf_common_master_script = append(tf_common_master_script,"\n) >&/var/log/px-deploy/"+filename+"\n"...)
}
}
// add scripts from the "scripts" section of config.yaml to common master node script
for _,filename := range config.Scripts {
content, err := ioutil.ReadFile("/px-deploy/.px-deploy/scripts/"+filename)
if err == nil {
tf_common_master_script = append(tf_common_master_script,"(\n"...)
tf_common_master_script = append(tf_common_master_script,"echo \"Started $(date)\"\n"...)
tf_common_master_script = append(tf_common_master_script,content...)
tf_common_master_script = append(tf_common_master_script,"echo \"Finished $(date)\"\n"...)
tf_common_master_script = append(tf_common_master_script,"\n) >&/var/log/px-deploy/"+filename+"\n"...)
}
}
// add post_script if defined
if config.Post_Script != "" {
content, err := ioutil.ReadFile("/px-deploy/.px-deploy/scripts/"+config.Post_Script)
if err == nil {
tf_post_script = append(tf_post_script,"(\n"...)
tf_post_script = append(tf_post_script,"echo \"Started $(date)\"\n"...)
tf_post_script = append(tf_post_script,content...)
tf_post_script = append(tf_post_script,"echo \"Finished $(date)\"\n"...)
tf_post_script = append(tf_post_script,"\n) >&/var/log/px-deploy/"+config.Post_Script+"\n"...)
}
} else {
tf_post_script = nil
}
// TODO if yaml['platform'] == "ocp4" or yaml['platform'] == "eks" or yaml['platform'] == "gke" or yaml['platform'] == "aks" then yaml['nodes'] = 0 end
if config.Platform == "ocp4" {
config.Nodes="0"
} else if config.Platform == "eks" {
config.Nodes="0"
}
Clusters, err := strconv.Atoi(config.Clusters)
Nodes, err := strconv.Atoi(config.Nodes)
// loop clusters and add master name/ip to tf var
for c := 1; c <= Clusters ; c++ {
masternum := strconv.Itoa(c)
net := strconv.Itoa(c+100)
tf_var_masters = append(tf_var_masters," master-"+masternum+" = {")
tf_var_masters = append(tf_var_masters," ip_address= \""+subnet+net+".90\"")
tf_var_masters = append(tf_var_masters," cluster= \""+masternum+"\"")
tf_var_masters = append(tf_var_masters," }")
tf_master_script = tf_common_master_script
tf_cluster_aws_type = config.Aws_Type
// if exist, apply individual scripts/aws_type settings for nodes of a cluster
for _, clusterconf := range config.Cluster {
if clusterconf.Id == c {
for _,filename := range clusterconf.Scripts {
content, err := ioutil.ReadFile("/px-deploy/.px-deploy/scripts/"+filename)
if err == nil {
tf_master_script = append(tf_master_script,"(\n"...)
tf_master_script = append(tf_master_script,content...)
tf_master_script = append(tf_master_script,"\n) >&/var/log/px-deploy/"+filename+"\n"...)
}
}
//is there a cluster specific aws_type override? if not, set from generic config
if clusterconf.Aws_Type != "" {
tf_cluster_aws_type = clusterconf.Aws_Type
}
}
}
// add post_script if defined
if tf_post_script != nil {
tf_master_script = append(tf_master_script,tf_post_script...)
}
// after running all scripts create file in /var/log/px-deploy/completed
tf_master_script = append(tf_master_script,"export IP=$(curl -s https://ipinfo.io/ip)\n"...)
tf_master_script = append(tf_master_script,"echo \"master-"+masternum+" $IP \" >> /var/log/px-deploy/completed/tracking \n"...)
//write master script for cluster
err := os.WriteFile("/px-deploy/.px-deploy/tf-deployments/" + config.Name + "/master-" +masternum , tf_master_script, 0666)
if err != nil {
die(err.Error())
}
// loop nodes of cluster, add node name/ip to tf var and write individual cloud-init scripts file
for n :=1; n <= Nodes ; n++ {
nodenum := strconv.Itoa(n)
nodeip := strconv.Itoa(n+100)
tf_var_nodes = append(tf_var_nodes," node-"+masternum+"-"+nodenum+" = { ")
tf_var_nodes = append(tf_var_nodes," ip_address = \""+subnet+net+"."+nodeip+"\"")
tf_var_nodes = append(tf_var_nodes," instance_type = \""+tf_cluster_aws_type+"\"")
tf_var_nodes = append(tf_var_nodes," cluster = \""+masternum+"\"")
tf_var_nodes = append(tf_var_nodes," }")
tf_individual_node_script = tf_node_script
tf_individual_node_script = append(tf_individual_node_script, "export IP=$(curl -s https://ipinfo.io/ip)\n"...)
tf_individual_node_script = append(tf_individual_node_script, "echo \"echo 'node-"+masternum+"-"+nodenum+" $IP' >> /var/log/px-deploy/completed/tracking \" | ssh root@master-"+masternum+" \n"...)
err := os.WriteFile("/px-deploy/.px-deploy/tf-deployments/" + config.Name + "/node-" +masternum+"-"+nodenum , tf_individual_node_script, 0666)
if err != nil {
die(err.Error())
}
// create EBS definition for each single node
for i,val := range tf_var_ebs_common {
tf_var_ebs = append(tf_var_ebs," node-"+masternum+"-"+nodenum+"-ebs-"+strconv.Itoa(i)+" = {")
tf_var_ebs = append(tf_var_ebs," node = \"node-"+masternum+"-"+nodenum+"\"")
tf_var_ebs = append(tf_var_ebs,val)
tf_var_ebs = append(tf_var_ebs," }")
}
}
}
// close ebs definition
tf_var_ebs = append(tf_var_ebs,"}\n")
// get PXDUSER env and apply to tf_variables
pxduser = os.Getenv("PXDUSER")
if (pxduser != "") {
tf_variables = append (tf_variables, "PXDUSER = \"" + pxduser + "\"")
}
// build terraform variable file
tf_variables = append (tf_variables, "config_name = \"" + config.Name + "\"")
tf_variables = append (tf_variables, "aws_region = \"" + config.Aws_Region + "\"")
tf_variables = append (tf_variables, "aws_instance_type = \"" + config.Aws_Type + "\"")
tf_variables = append (tf_variables, "masters = {")
for _, value := range tf_var_masters {
tf_variables = append (tf_variables, value)
}
tf_variables = append (tf_variables, "}")
tf_variables = append (tf_variables, "nodes = {")
for _, value := range tf_var_nodes {
tf_variables = append (tf_variables, value)
}
tf_variables = append (tf_variables, "}")
// last item of variables is node ebs definition
tf_variables = append (tf_variables,tf_var_ebs...)
write_tf_file(config.Name, ".tfvars",tf_variables)
// now run terraform plan & terraform apply
fmt.Println(White+"running terraform PLAN"+Reset)
cmd := exec.Command("terraform","-chdir=/px-deploy/.px-deploy/tf-deployments/"+config.Name, "plan", "-input=false", "-out=tfplan", "-var-file",".tfvars")
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
fmt.Println(Yellow+"ERROR: terraform plan failed. Check validity of terraform scripts"+Reset)
die(err.Error())
} else {
fmt.Println(White+"running terraform APPLY"+Reset)
cmd:=exec.Command("terraform","-chdir=/px-deploy/.px-deploy/tf-deployments/"+config.Name, "apply", "-input=false", "-auto-approve", "tfplan")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
errapply = cmd.Run()
if errapply != nil {
fmt.Println(Yellow+"ERROR: terraform apply failed. Check validity of terraform scripts"+Reset)
die(errapply.Error())
}
// apply the terraform aws-returns-generated to deployment yml file (maintains compatibility to px-deploy behaviour, maybe not needed any longer)
content, err := ioutil.ReadFile("/px-deploy/.px-deploy/tf-deployments/"+config.Name+"/aws-returns-generated.yaml")
file,err := os.OpenFile("/px-deploy/.px-deploy/deployments/" + config.Name+".yml", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
die(err.Error())
}
defer file.Close()
_, err = file.WriteString(string(content))
if err != nil {
die(err.Error())
}
fmt.Println(Yellow + "Terraform infrastructure creation done. Please check master/node readiness using: px-deploy status -n "+config.Name+Reset)
}
}
case "aws":
{
output, err = exec.Command("bash", "-c", `
aws configure set default.region `+config.Aws_Region+`
yes | ssh-keygen -q -t rsa -b 2048 -f keys/id_rsa.aws.`+config.Name+` -N ''
aws ec2 describe-regions >&/dev/null
[ $? -ne 0 ] && echo "Invalid AWS credentials" && exit 1
aws ec2 describe-instance-types --instance-types `+config.Aws_Type+`>&/dev/null
[ $? -ne 0 ] && echo "Invalid AWS type '`+config.Aws_Type+`' for region '`+config.Aws_Region+`'" && exit 1
echo "Provisioning as user $(aws --output text iam get-user --query User.[UserName,UserId] --output text | sed 's/ /(/;s/$/)/')"
aws ec2 delete-key-pair --key-name px-deploy.`+config.Name+` >&/dev/null
aws ec2 import-key-pair --key-name px-deploy.`+config.Name+` --public-key-material file://keys/id_rsa.aws.`+config.Name+`.pub >&/dev/null
_AWS_vpc=$(aws --output text ec2 create-vpc --cidr-block 192.168.0.0/16 --query Vpc.VpcId)
[ $? -ne 0 ] && echo "Failed to create VPC in region '`+config.Aws_Region+`'" && exit 1
_AWS_subnet=$(aws --output text ec2 create-subnet --vpc-id $_AWS_vpc --cidr-block 192.168.0.0/16 --query Subnet.SubnetId)
_AWS_gw=$(aws --output text ec2 create-internet-gateway --query InternetGateway.InternetGatewayId)
aws ec2 attach-internet-gateway --vpc-id $_AWS_vpc --internet-gateway-id $_AWS_gw
_AWS_routetable=$(aws --output text ec2 create-route-table --vpc-id $_AWS_vpc --query RouteTable.RouteTableId)
aws ec2 create-route --route-table-id $_AWS_routetable --destination-cidr-block 0.0.0.0/0 --gateway-id $_AWS_gw >/dev/null
aws ec2 associate-route-table --subnet-id $_AWS_subnet --route-table-id $_AWS_routetable >/dev/null
_AWS_sg=$(aws --output text ec2 create-security-group --group-name px-deploy --description "Security group for px-deploy" --vpc-id $_AWS_vpc --query GroupId)
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 22 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 80 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 443 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 2382 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 5900 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 8080 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 8443 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol tcp --port 30000-32767 --cidr 0.0.0.0/0 &
aws ec2 authorize-security-group-ingress --group-id $_AWS_sg --protocol all --cidr 192.168.0.0/16 &
aws ec2 create-tags --resources $_AWS_vpc $_AWS_subnet $_AWS_gw $_AWS_routetable $_AWS_sg --tags Key=px-deploy_name,Value=`+config.Name+` &
aws ec2 create-tags --resources $_AWS_vpc --tags Key=Name,Value=px-deploy.`+config.Name+` &
_AWS_ami=$(aws --output text ec2 describe-images --include-deprecated --owners 679593333241 --filters Name=name,Values='CentOS Linux 7 x86_64 HVM EBS*' Name=architecture,Values=x86_64 Name=root-device-type,Values=ebs --query 'sort_by(Images, &Name)[-1].ImageId')
wait
echo aws__vpc: $_AWS_vpc >>deployments/`+config.Name+`.yml
echo aws__sg: $_AWS_sg >>deployments/`+config.Name+`.yml
echo aws__subnet: $_AWS_subnet >>deployments/`+config.Name+`.yml
echo aws__gw: $_AWS_gw >>deployments/`+config.Name+`.yml
echo aws__routetable: $_AWS_routetable >>deployments/`+config.Name+`.yml
echo aws__ami: $_AWS_ami >>deployments/`+config.Name+`.yml
`).CombinedOutput()
}
case "gcp":
{
output, _ = exec.Command("bash", "-c", `
yes | ssh-keygen -q -t rsa -b 2048 -f keys/id_rsa.gcp.`+config.Name+` -N ''
_GCP_project=pxd-$(uuidgen | tr -d -- - | cut -b 1-26 | tr 'A-Z' 'a-z')
gcloud projects create $_GCP_project --labels px-deploy_name=`+config.Name+`
account=$(gcloud alpha billing accounts list | tail -1 | cut -f 1 -d " ")
gcloud alpha billing projects link $_GCP_project --billing-account $account
gcloud services enable compute.googleapis.com --project $_GCP_project
gcloud compute networks create px-net --project $_GCP_project
gcloud compute networks subnets create --range 192.168.0.0/16 --network px-net px-subnet --region `+config.Gcp_Region+` --project $_GCP_project
gcloud compute firewall-rules create allow-internal --allow=tcp,udp,icmp --source-ranges=192.168.0.0/16 --network px-net --project $_GCP_project &
gcloud compute firewall-rules create allow-external --allow=tcp:22,tcp:80,tcp:443,tcp:6443,tcp:5900 --network px-net --project $_GCP_project &
gcloud compute project-info add-metadata --metadata "ssh-keys=centos:$(cat keys/id_rsa.gcp.`+config.Name+`.pub)" --project $_GCP_project &
service_account=$(gcloud iam service-accounts list --project $_GCP_project --format 'flattened(email)' | tail -1 | cut -f 2 -d " ")
_GCP_key=$(gcloud iam service-accounts keys create /dev/stdout --iam-account $service_account | base64 -w0)
wait
echo gcp__project: $_GCP_project >>deployments/`+config.Name+`.yml
echo gcp__key: $_GCP_key >>deployments/`+config.Name+`.yml
`).CombinedOutput()
}
case "azure":
{
output, _ = exec.Command("bash", "-c", `
az account get-access-token
az configure --defaults location=`+config.Azure_Region+`
yes | ssh-keygen -q -t rsa -b 2048 -f keys/id_rsa.azure.`+config.Name+` -N ''
_AZURE_group=pxd-$(uuidgen)
az group create -g $_AZURE_group --output none
az network vnet create --name $_AZURE_group --resource-group $_AZURE_group --address-prefix 192.168.0.0/16 --subnet-name $_AZURE_group --subnet-prefixes 192.168.0.0/16 --output none
az network private-dns zone create -g $_AZURE_group -n $_AZURE_group.pxd --output none
az network private-dns link vnet create -g $_AZURE_group -n $_AZURE_group -z $_AZURE_group.pxd -v $_AZURE_group -e true --output none
_AZURE_subscription=$(az account show --query id --output tsv)
echo $(az ad sp create-for-rbac -n $_AZURE_group --query "[appId,password,tenant]" --output tsv 2>/dev/null) | while read _AZURE_client _AZURE_secret _AZURE_tenant ; do
echo azure__client: $_AZURE_client
echo azure__secret: $_AZURE_secret
echo azure__tenant: $_AZURE_tenant
echo azure__subscription: $_AZURE_subscription
done >>deployments/`+config.Name+`.yml
echo azure__group: $_AZURE_group >>deployments/`+config.Name+`.yml
`).CombinedOutput()
}
case "vsphere":
{
output, _ = exec.Command("bash", "-c", `
yes | ssh-keygen -q -t rsa -b 2048 -f keys/id_rsa.vsphere.`+config.Name+` -N ''
_Vsphere_userdata=$(echo -e '#cloud-config\nusers:\n - default\n - name: centos\n primary_group: centos\n sudo: ALL=(ALL) NOPASSWD:ALL\n groups: sudo, wheel\n ssh_import_id: None\n lock_passwd: true\n ssh_authorized_keys:\n - '$(cat keys/id_rsa.vsphere.`+config.Name+`.pub) | base64 -w0)
echo vsphere__userdata: $_Vsphere_userdata >>deployments/`+config.Name+`.yml
`).CombinedOutput()
}
default:
die("Invalid cloud '" + config.Cloud + "'")
}
if (config.Quiet != "true") {