-
Notifications
You must be signed in to change notification settings - Fork 18
/
instance_create.go
253 lines (215 loc) · 7.85 KB
/
instance_create.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
package cmd
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"path"
"strings"
"time"
egoscale "github.com/exoscale/egoscale/v2"
exoapi "github.com/exoscale/egoscale/v2/api"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
)
type instanceCreateCmd struct {
cliCommandSettings `cli-cmd:"-"`
_ bool `cli-cmd:"create"`
Name string `cli-arg:"#" cli-usage:"NAME"`
AntiAffinityGroups []string `cli-flag:"anti-affinity-group" cli-usage:"instance Anti-Affinity Group NAME|ID (can be specified multiple times)"`
CloudInitFile string `cli-flag:"cloud-init" cli-usage:"instance cloud-init user data configuration file path"`
CloudInitCompress bool `cli-flag:"cloud-init-compress" cli-usage:"compress instance cloud-init user data"`
DeployTarget string `cli-usage:"instance Deploy Target NAME|ID"`
DiskSize int64 `cli-usage:"instance disk size"`
IPv6 bool `cli-flag:"ipv6" cli-usage:"enable IPv6 on instance"`
InstanceType string `cli-usage:"instance type (format: [FAMILY.]SIZE)"`
Labels map[string]string `cli-flag:"label" cli-usage:"instance label (format: key=value)"`
PrivateNetworks []string `cli-flag:"private-network" cli-usage:"instance Private Network NAME|ID (can be specified multiple times)"`
SSHKey string `cli-flag:"ssh-key" cli-usage:"SSH key to deploy on the instance"`
SecurityGroups []string `cli-flag:"security-group" cli-usage:"instance Security Group NAME|ID (can be specified multiple times)"`
Template string `cli-usage:"instance template NAME|ID"`
TemplateVisibility string `cli-usage:"instance template visibility (public|private)"`
Zone string `cli-short:"z" cli-usage:"instance zone"`
}
func (c *instanceCreateCmd) cmdAliases() []string { return gCreateAlias }
func (c *instanceCreateCmd) cmdShort() string { return "Create a Compute instance" }
func (c *instanceCreateCmd) cmdLong() string {
return fmt.Sprintf(`This command creates a Compute instance.
Supported Compute instance type families: %s
Supported Compute instance type sizes: %s
Supported output template annotations: %s`,
strings.Join(instanceTypeFamilies, ", "),
strings.Join(instanceTypeSizes, ", "),
strings.Join(outputterTemplateAnnotations(&instanceShowOutput{}), ", "))
}
func (c *instanceCreateCmd) cmdPreRun(cmd *cobra.Command, args []string) error {
cmdSetZoneFlagFromDefault(cmd)
cmdSetTemplateFlagFromDefault(cmd)
return cliCommandDefaultPreRun(c, cmd, args)
}
func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error {
var (
singleUseSSHPrivateKey *rsa.PrivateKey
singleUseSSHPublicKey ssh.PublicKey
sshKey *egoscale.SSHKey
)
instance := &egoscale.Instance{
DiskSize: &c.DiskSize,
IPv6Enabled: &c.IPv6,
Labels: func() (v *map[string]string) {
if len(c.Labels) > 0 {
return &c.Labels
}
return
}(),
Name: &c.Name,
SSHKey: nonEmptyStringPtr(c.SSHKey),
}
ctx := exoapi.WithEndpoint(gContext, exoapi.NewReqEndpoint(gCurrentAccount.Environment, c.Zone))
if l := len(c.AntiAffinityGroups); l > 0 {
antiAffinityGroupIDs := make([]string, l)
for i := range c.AntiAffinityGroups {
antiAffinityGroup, err := cs.FindAntiAffinityGroup(ctx, c.Zone, c.AntiAffinityGroups[i])
if err != nil {
return fmt.Errorf("error retrieving Anti-Affinity Group: %w", err)
}
antiAffinityGroupIDs[i] = *antiAffinityGroup.ID
}
instance.AntiAffinityGroupIDs = &antiAffinityGroupIDs
}
if c.DeployTarget != "" {
deployTarget, err := cs.FindDeployTarget(ctx, c.Zone, c.DeployTarget)
if err != nil {
return fmt.Errorf("error retrieving Deploy Target: %w", err)
}
instance.DeployTargetID = deployTarget.ID
}
instanceType, err := cs.FindInstanceType(ctx, c.Zone, c.InstanceType)
if err != nil {
return fmt.Errorf("error retrieving instance type: %w", err)
}
instance.InstanceTypeID = instanceType.ID
privateNetworks := make([]*egoscale.PrivateNetwork, len(c.PrivateNetworks))
if l := len(c.PrivateNetworks); l > 0 {
for i := range c.PrivateNetworks {
privateNetwork, err := cs.FindPrivateNetwork(ctx, c.Zone, c.PrivateNetworks[i])
if err != nil {
return fmt.Errorf("error retrieving Private Network: %w", err)
}
privateNetworks[i] = privateNetwork
}
}
if l := len(c.SecurityGroups); l > 0 {
securityGroupIDs := make([]string, l)
for i := range c.SecurityGroups {
securityGroup, err := cs.FindSecurityGroup(ctx, c.Zone, c.SecurityGroups[i])
if err != nil {
return fmt.Errorf("error retrieving Security Group: %w", err)
}
securityGroupIDs[i] = *securityGroup.ID
}
instance.SecurityGroupIDs = &securityGroupIDs
}
if instance.SSHKey == nil && gCurrentAccount.DefaultSSHKey != "" {
instance.SSHKey = &gCurrentAccount.DefaultSSHKey
}
// Generating a single-use SSH key pair for this instance.
if instance.SSHKey == nil {
singleUseSSHPrivateKey, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return fmt.Errorf("error generating SSH private key: %w", err)
}
if err = singleUseSSHPrivateKey.Validate(); err != nil {
return fmt.Errorf("error generating SSH private key: %w", err)
}
singleUseSSHPublicKey, err = ssh.NewPublicKey(&singleUseSSHPrivateKey.PublicKey)
if err != nil {
return fmt.Errorf("error generating SSH public key: %w", err)
}
sshKey, err = cs.RegisterSSHKey(
ctx,
c.Zone,
fmt.Sprintf("%s-%d", c.Name, time.Now().Unix()),
string(ssh.MarshalAuthorizedKey(singleUseSSHPublicKey)),
)
if err != nil {
return fmt.Errorf("error registering SSH key: %w", err)
}
instance.SSHKey = sshKey.Name
}
templates, err := cs.ListTemplates(
ctx,
c.Zone,
egoscale.ListTemplatesWithVisibility(c.TemplateVisibility),
)
if err != nil {
return fmt.Errorf("error retrieving templates: %w", err)
}
for _, template := range templates {
if *template.ID == c.Template || *template.Name == c.Template {
instance.TemplateID = template.ID
break
}
}
if instance.TemplateID == nil {
return fmt.Errorf("no template %q found with visibility %s", c.Template, c.TemplateVisibility)
}
if c.CloudInitFile != "" {
userData, err := getUserDataFromFile(c.CloudInitFile, c.CloudInitCompress)
if err != nil {
return fmt.Errorf("error parsing cloud-init user data: %w", err)
}
instance.UserData = &userData
}
decorateAsyncOperation(fmt.Sprintf("Creating instance %q...", c.Name), func() {
instance, err = cs.CreateInstance(ctx, c.Zone, instance)
if err != nil {
return
}
for _, p := range privateNetworks {
if err = cs.AttachInstanceToPrivateNetwork(ctx, c.Zone, instance, p); err != nil {
return
}
}
})
if err != nil {
return err
}
if singleUseSSHPrivateKey != nil {
privateKeyFilePath := getInstanceSSHKeyPath(*instance.ID)
if err = os.MkdirAll(path.Dir(privateKeyFilePath), 0o700); err != nil {
return fmt.Errorf("error writing SSH private key file: %w", err)
}
if err = os.WriteFile(
privateKeyFilePath,
pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(singleUseSSHPrivateKey),
}),
0o600,
); err != nil {
return fmt.Errorf("error writing SSH private key file: %w", err)
}
if err = cs.DeleteSSHKey(ctx, c.Zone, sshKey); err != nil {
return fmt.Errorf("error deleting SSH key: %w", err)
}
}
if !gQuiet {
return (&instanceShowCmd{
cliCommandSettings: c.cliCommandSettings,
Instance: *instance.ID,
Zone: c.Zone,
}).cmdRun(nil, nil)
}
return nil
}
func init() {
cobra.CheckErr(registerCLICommand(instanceCmd, &instanceCreateCmd{
cliCommandSettings: defaultCLICmdSettings(),
DiskSize: 50,
InstanceType: fmt.Sprintf("%s.%s", defaultInstanceTypeFamily, defaultInstanceType),
TemplateVisibility: defaultTemplateVisibility,
}))
}