-
Notifications
You must be signed in to change notification settings - Fork 20
/
vm.go
109 lines (90 loc) · 2.28 KB
/
vm.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
package cmd
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
// vmCmd represents the vm command
var vmCmd = &cobra.Command{
Use: "vm",
Short: "Virtual machines management",
}
func getVirtualMachineByNameOrID(name string) (*egoscale.VirtualMachine, error) {
vmQuery := egoscale.VirtualMachine{}
id, err := egoscale.ParseUUID(name)
if err != nil {
vmQuery.Name = name
} else {
vmQuery.ID = id
}
vms, err := cs.ListWithContext(gContext, vmQuery)
if err != nil {
return nil, err
}
var vm *egoscale.VirtualMachine
switch len(vms) {
case 0:
return nil, fmt.Errorf("no VMs has been found")
case 1:
vm = vms[0].(*egoscale.VirtualMachine)
default:
names := []string{}
for _, i := range vms {
v := i.(*egoscale.VirtualMachine)
if v.Name != vmQuery.Name {
continue
}
vm = v
names = append(names, fmt.Sprintf("\t%s\t%s\t%s", v.ID.String(), v.ZoneName, v.IP()))
}
if len(names) == 1 {
break
}
fmt.Println("More than one VM has been found, use the ID instead:")
for _, name := range names {
fmt.Println(name)
}
return nil, fmt.Errorf("abort vm name %q is ambiguous", vmQuery.Name)
}
return vm, nil
}
func getSecurityGroup(vm *egoscale.VirtualMachine) []string {
sgs := []string{}
for _, sgN := range vm.SecurityGroup {
sgs = append(sgs, sgN.Name)
}
return sgs
}
func getKeyPairPath(vmID string) string {
return path.Join(gConfigFolder, "instances", vmID, "id_rsa")
}
func saveKeyPair(keyPairs *egoscale.SSHKeyPair, vmID egoscale.UUID) {
filePath := getKeyPairPath(vmID.String())
folder := path.Dir(filePath)
if _, err := os.Stat(folder); os.IsNotExist(err) {
if err := os.MkdirAll(folder, os.ModePerm); err != nil {
log.Fatal(err)
}
}
if _, err := os.Stat(filePath); os.IsNotExist(err) {
if err := ioutil.WriteFile(filePath, []byte(keyPairs.PrivateKey), 0600); err != nil {
log.Fatalf("SSH private key could not be written: %s", err)
}
}
}
func deleteKeyPair(vmID egoscale.UUID) error {
folder := getKeyPairPath(vmID.String())
if _, err := os.Stat(folder); !os.IsNotExist(err) {
if err := os.RemoveAll(folder); err != nil {
return fmt.Errorf("the SSH private key could not be deleted: %s", err)
}
}
return nil
}
func init() {
RootCmd.AddCommand(vmCmd)
}