forked from schubergphilis/packer-cloudstack
/
builder.go
366 lines (304 loc) · 10.5 KB
/
builder.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
// The cloudstack package contains a packer.Builder implementation
// that builds Cloudstack images (templates).
package cloudstack
import (
"errors"
"fmt"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/common"
"github.com/mitchellh/packer/packer"
"github.com/morpheu/gopherstack"
"log"
"os"
"time"
)
// The unique id for the builder
const BuilderId = "morpheu.cloudstack"
// Configuration tells the builder the credentials to use while
// communicating with Cloudstack and describes the template you are
// creating
type config struct {
common.PackerConfig `mapstructure:",squash"`
APIURL string `mapstructure:"api_url"`
APIKey string `mapstructure:"api_key"`
SecretKey string `mapstructure:"secret_key"`
RawSSHTimeout string `mapstructure:"ssh_timeout"`
RawStateTimeout string `mapstructure:"state_timeout"`
// Time to wait before issuing the API call to detach the
// bootstrap/installation ISO from the virtual machine.
RawDetachISOWait string `mapstructure:"detach_iso_wait"`
InsecureSkipVerify bool `mapstructure:"insecure_skip_verify"`
SSHUsername string `mapstructure:"ssh_username"`
SSHPort uint `mapstructure:"ssh_port"`
SSHKeyPath string `mapstructure:"ssh_key_path"`
SSHPassword string `mapstructure:"ssh_password"`
// These are unexported since they're set by other fields
// being set.
sshTimeout time.Duration
stateTimeout time.Duration
detachISOWait time.Duration
HTTPDir string `mapstructure:"http_directory"`
HTTPPortMin uint `mapstructure:"http_port_min"`
HTTPPortMax uint `mapstructure:"http_port_max"`
// Neccessary settings for Cloudstack to be able to spin up
// Virtual Machine with either template or a ISO.
ProjectId string `mapstructure:"project_id"`
ServiceOfferingId string `mapstructure:"service_offering_id"`
TemplateId string `mapstructure:"template_id"`
ZoneId string `mapstructure:"zone_id"`
NetworkIds []string `mapstructure:"network_ids"`
DiskOfferingId string `mapstructure:"disk_offering_id"`
UserData string `mapstructure:"user_data"`
Hypervisor string `mapstructure:"hypervisor"`
Size string `mapstructure:"size"`
// Tell Cloudstack under which name, description to save the
// template.
TemplateName string `mapstructure:"template_name"`
TemplateDisplayText string `mapstructure:"template_display_text"`
TemplateOSId string `mapstructure:"template_os_id"`
TemplateScalable bool `mapstructure:"template_scalable"`
TemplatePublic bool `mapstructure:"template_public"`
TemplateFeatured bool `mapstructure:"template_featured"`
TemplateExtractable bool `mapstructure:"template_extractable"`
TemplatePasswordEnabled bool `mapstructure:"template_password_enabled"`
TemplateTags map[string]string `mapstructure:"template_tags"`
tpl *packer.ConfigTemplate
}
type Builder struct {
config config
runner multistep.Runner
}
func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
md, err := common.DecodeConfig(&b.config, raws...)
if err != nil {
return nil, err
}
b.config.tpl, err = packer.NewConfigTemplate()
if err != nil {
return nil, err
}
b.config.tpl.UserVars = b.config.PackerUserVars
// Accumulate any errors
errs := common.CheckUnusedConfig(md)
if b.config.APIURL == "" {
// Default to environment variable for API URL
b.config.APIURL = os.Getenv("CLOUDSTACK_API_URL")
}
if b.config.APIKey == "" {
// Default to environment variable for API key
b.config.APIKey = os.Getenv("CLOUDSTACK_API_KEY")
}
if b.config.SecretKey == "" {
// Default to environment variable for API secret
b.config.SecretKey = os.Getenv("CLOUDSTACK_SECRET_KEY")
}
if b.config.HTTPPortMin == 0 {
b.config.HTTPPortMin = 8000
}
if b.config.HTTPPortMax == 0 {
b.config.HTTPPortMax = 9000
}
if b.config.TemplateName == "" {
// Default to packer-{{ unix timestamp (utc) }}
b.config.TemplateName = "packer-{{timestamp}}"
}
if b.config.TemplateDisplayText == "" {
b.config.TemplateDisplayText = "Packer_Generated_Template"
}
if b.config.SSHUsername == "" {
// Default to "root". You can override this if your
// source template has a different user account.
b.config.SSHUsername = "root"
}
if b.config.SSHPort == 0 {
// Default to port 22
b.config.SSHPort = 22
}
if b.config.RawSSHTimeout == "" {
// Default to 10 minute timeouts
b.config.RawSSHTimeout = "10m"
}
if b.config.RawStateTimeout == "" {
// Default to 5 minute timeouts waiting for desired
// state. i.e waiting for virtual machine to become
// active
b.config.RawStateTimeout = "5m"
}
if b.config.RawDetachISOWait == "" {
// Default to wait 10 seconds before detaching the ISO
// from the started virtual machine.
b.config.RawDetachISOWait = "10s"
}
templates := map[string]*string{
"api_url": &b.config.APIURL,
"api_key": &b.config.APIKey,
"secret_key": &b.config.SecretKey,
"ssh_timeout": &b.config.RawSSHTimeout,
"state_timeout": &b.config.RawStateTimeout,
"detach_iso_wait": &b.config.RawDetachISOWait,
"ssh_username": &b.config.SSHUsername,
"ssh_key_path": &b.config.SSHKeyPath,
"ssh_password": &b.config.SSHPassword,
"http_directory": &b.config.HTTPDir,
"service_offering_id": &b.config.ServiceOfferingId,
"project_id": &b.config.ProjectId,
"template_id": &b.config.TemplateId,
"zone_id": &b.config.ZoneId,
"disk_offering_id": &b.config.DiskOfferingId,
"hypervisor": &b.config.Hypervisor,
"template_name": &b.config.TemplateName,
"template_display_text": &b.config.TemplateDisplayText,
"template_os_id": &b.config.TemplateOSId,
}
for n, ptr := range templates {
var err error
*ptr, err = b.config.tpl.Process(*ptr, nil)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Error processing %s: %s", n, err))
}
}
validates := map[string]*string{
"user_data": &b.config.UserData,
}
for n, ptr := range validates {
if err := b.config.tpl.Validate(*ptr); err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Error parsing %s: %s", n, err))
}
}
if b.config.HTTPPortMin > b.config.HTTPPortMax {
errs = packer.MultiErrorAppend(
errs, errors.New("http_port_min must be less than http_port_max"))
}
// Required configurations that will display errors if not set
if b.config.APIURL == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("CLOUDSTACK_API_URL in env (APIURL in json) must be specified"))
}
if b.config.APIKey == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("CLOUDSTACK_API_KEY in env (APIKey in json) must be specified"))
}
if b.config.SecretKey == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("CLOUDSTACK_SECRET_KEY in env (SecretKey in json) must be specified"))
}
if b.config.ServiceOfferingId == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("service_offering_id must be specified"))
}
if b.config.TemplateId == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("template_id must be specified"))
}
if b.config.ZoneId == "" {
errs = packer.MultiErrorAppend(
errs, errors.New("zone_id must be specified"))
}
sshTimeout, err := time.ParseDuration(b.config.RawSSHTimeout)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Failed parsing ssh_timeout: %s", err))
}
b.config.sshTimeout = sshTimeout
detachISOWait, err := time.ParseDuration(b.config.RawDetachISOWait)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Failed parsing iso_detach_wait: %s", err))
}
b.config.detachISOWait = detachISOWait
stateTimeout, err := time.ParseDuration(b.config.RawStateTimeout)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Failed parsing state_timeout: %s", err))
}
b.config.stateTimeout = stateTimeout
newTags := make(map[string]string)
for k, v := range b.config.TemplateTags {
k, err := b.config.tpl.Process(k, nil)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Error processing tag key %s: %s", k, err))
continue
}
v, err := b.config.tpl.Process(v, nil)
if err != nil {
errs = packer.MultiErrorAppend(
errs, fmt.Errorf("Error processing tag value '%s': %s", v, err))
continue
}
newTags[k] = v
}
b.config.TemplateTags = newTags
if errs != nil && len(errs.Errors) > 0 {
return nil, errs
}
common.ScrubConfig(b.config, b.config.APIKey, b.config.SecretKey)
return nil, nil
}
func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
// Initialize the Cloudstack API client
client := gopherstack.CloudstackClient{}.New(b.config.APIURL, b.config.APIKey,
b.config.SecretKey, b.config.InsecureSkipVerify)
// Set up the state
state := new(multistep.BasicStateBag)
state.Put("config", b.config)
state.Put("client", client)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps
steps := []multistep.Step{
new(stepHTTPServer),
new(stepCreateSSHKeyPair),
new(stepDeployVirtualMachine),
new(stepVirtualMachineState),
new(stepDetachIso),
&common.StepConnectSSH{
SSHAddress: sshAddress,
SSHConfig: sshConfig,
SSHWaitTimeout: b.config.sshTimeout,
},
new(common.StepProvision),
new(stepStopVirtualMachine),
new(stepCreateTemplate),
new(stepCreateTags),
}
// Run the steps
if b.config.PackerDebug {
b.runner = &multistep.DebugRunner{
Steps: steps,
PauseFn: common.MultistepDebugFn(ui),
}
} else {
b.runner = &multistep.BasicRunner{Steps: steps}
}
b.runner.Run(state)
// If there was an error, return that
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
// If we were interrupted or cancelled, then just exit.
if _, ok := state.GetOk(multistep.StateCancelled); ok {
return nil, errors.New("Build was cancelled.")
}
if _, ok := state.GetOk(multistep.StateHalted); ok {
return nil, errors.New("Build was halted.")
}
if _, ok := state.GetOk("template_name"); !ok {
log.Println("Failed to find template_name in state. Bug?")
return nil, nil
}
artifact := &Artifact{
templateName: state.Get("template_name").(string),
templateId: state.Get("template_id").(string),
client: client,
}
return artifact, nil
}
func (b *Builder) Cancel() {
if b.runner != nil {
log.Println("Cancelling the step runner...")
b.runner.Cancel()
}
}