forked from hashicorp/packer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
step_create_droplet.go
81 lines (67 loc) · 1.88 KB
/
step_create_droplet.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
package digitalocean
import (
"fmt"
"github.com/digitalocean/godo"
"github.com/mitchellh/multistep"
"github.com/mitchellh/packer/packer"
"io/ioutil"
)
type stepCreateDroplet struct {
dropletId int
}
func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction {
client := state.Get("client").(*godo.Client)
ui := state.Get("ui").(packer.Ui)
c := state.Get("config").(Config)
sshKeyId := state.Get("ssh_key_id").(int)
// Create the droplet based on configuration
ui.Say("Creating droplet...")
userData := c.UserData
if c.UserDataFile != "" {
contents, err := ioutil.ReadFile(c.UserDataFile)
if err != nil {
state.Put("error", fmt.Errorf("Problem reading user data file: %s", err))
return multistep.ActionHalt
}
userData = string(contents)
}
droplet, _, err := client.Droplets.Create(&godo.DropletCreateRequest{
Name: c.DropletName,
Region: c.Region,
Size: c.Size,
Image: godo.DropletCreateImage{
Slug: c.Image,
},
SSHKeys: []godo.DropletCreateSSHKey{
{ID: int(sshKeyId)},
},
PrivateNetworking: c.PrivateNetworking,
UserData: userData,
})
if err != nil {
err := fmt.Errorf("Error creating droplet: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
// We use this in cleanup
s.dropletId = droplet.ID
// Store the droplet id for later
state.Put("droplet_id", droplet.ID)
return multistep.ActionContinue
}
func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) {
// If the dropletid isn't there, we probably never created it
if s.dropletId == 0 {
return
}
client := state.Get("client").(*godo.Client)
ui := state.Get("ui").(packer.Ui)
// Destroy the droplet we just created
ui.Say("Destroying droplet...")
_, err := client.Droplets.Delete(s.dropletId)
if err != nil {
ui.Error(fmt.Sprintf(
"Error destroying droplet. Please destroy it manually: %s", err))
}
}