-
Notifications
You must be signed in to change notification settings - Fork 2
/
vms.go
84 lines (62 loc) · 1.62 KB
/
vms.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
package main
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"gopkg.in/AlecAivazis/survey.v1"
)
type vmDetails struct {
Name string `json:"name"`
Zone string `json:"zone"`
}
func getGcloudVMs(project projectDetails) (vms []vmDetails, err error) {
projectArg := fmt.Sprintf("--project=%s", project.ProjectID)
cmd := execCommand("gcloud", "compute", "instances", "list", projectArg, "--format=json")
output, err := cmd.CombinedOutput()
if err != nil {
return
}
json.Unmarshal([]byte(output), &vms)
for i, vm := range vms {
splits := strings.Split(vm.Zone, "/")
vm.Zone = splits[len(splits)-1]
vms[i] = vm
}
return
}
func filterVMs(vms []vmDetails, vmFilter string) (filteredVMs []vmDetails) {
for _, vm := range vms {
if strings.Contains(vm.Name, vmFilter) {
filteredVMs = append(filteredVMs, vm)
}
}
return
}
func selectVM(vms []vmDetails) (vm vmDetails) {
var answer string
options := vmDetailsToSurvey(vms)
prompt := &survey.Select{
Message: "Select your VM:",
Options: options,
PageSize: pageSize,
}
survey.AskOne(prompt, &answer, nil)
vm = stringToVMDetails(answer)
return
}
func vmDetailsToSurvey(vms []vmDetails) (simplifiedVMs []string) {
for _, vm := range vms {
simplifiedVMs = append(simplifiedVMs, fmt.Sprintf("(%s) %s", vm.Zone, vm.Name))
}
return
}
func stringToVMDetails(surveyAnswer string) (vm vmDetails) {
r, _ := regexp.Compile("\\((.*)\\) (.*)")
results := r.FindStringSubmatch(surveyAnswer)
// Quick reminder as this always catches me, the first
// result (0) is the whole string string, not group match.
vm.Zone = results[1]
vm.Name = results[2]
return
}