2013-06-13 12:48:19 -04:00
|
|
|
package digitalocean
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2014-08-28 14:24:31 -04:00
|
|
|
|
2015-06-10 17:02:06 -04:00
|
|
|
"github.com/digitalocean/godo"
|
2013-06-13 12:48:19 -04:00
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
|
|
|
)
|
|
|
|
|
|
|
|
type stepCreateDroplet struct {
|
2015-06-10 17:02:06 -04:00
|
|
|
dropletId int
|
2013-06-13 12:48:19 -04:00
|
|
|
}
|
|
|
|
|
2013-08-31 15:25:08 -04:00
|
|
|
func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction {
|
2015-06-10 17:02:06 -04:00
|
|
|
client := state.Get("client").(*godo.Client)
|
2013-08-31 15:25:08 -04:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
2015-05-27 15:50:43 -04:00
|
|
|
c := state.Get("config").(Config)
|
2015-06-10 17:02:06 -04:00
|
|
|
sshKeyId := state.Get("ssh_key_id").(int)
|
2013-06-13 12:48:19 -04:00
|
|
|
|
|
|
|
// Create the droplet based on configuration
|
2015-06-10 17:02:06 -04:00
|
|
|
ui.Say("Creating droplet...")
|
|
|
|
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{
|
|
|
|
godo.DropletCreateSSHKey{ID: int(sshKeyId)},
|
|
|
|
},
|
|
|
|
PrivateNetworking: c.PrivateNetworking,
|
2015-06-10 22:29:48 -04:00
|
|
|
UserData: c.UserData,
|
2015-06-10 17:02:06 -04:00
|
|
|
})
|
2013-06-13 12:48:19 -04:00
|
|
|
if err != nil {
|
2013-06-20 00:00:51 -04:00
|
|
|
err := fmt.Errorf("Error creating droplet: %s", err)
|
2013-08-31 15:25:08 -04:00
|
|
|
state.Put("error", err)
|
2013-06-13 12:48:19 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
// We use this in cleanup
|
2015-06-10 17:02:06 -04:00
|
|
|
s.dropletId = droplet.ID
|
2013-06-13 12:48:19 -04:00
|
|
|
|
|
|
|
// Store the droplet id for later
|
2015-06-10 17:02:06 -04:00
|
|
|
state.Put("droplet_id", droplet.ID)
|
2013-06-13 12:48:19 -04:00
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2013-08-31 15:25:08 -04:00
|
|
|
func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) {
|
2013-06-13 12:48:19 -04:00
|
|
|
// If the dropletid isn't there, we probably never created it
|
|
|
|
if s.dropletId == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-10 17:02:06 -04:00
|
|
|
client := state.Get("client").(*godo.Client)
|
2013-08-31 15:25:08 -04:00
|
|
|
ui := state.Get("ui").(packer.Ui)
|
2013-06-13 12:48:19 -04:00
|
|
|
|
|
|
|
// Destroy the droplet we just created
|
|
|
|
ui.Say("Destroying droplet...")
|
2015-06-10 17:02:06 -04:00
|
|
|
_, err := client.Droplets.Delete(s.dropletId)
|
2013-06-13 12:48:19 -04:00
|
|
|
if err != nil {
|
|
|
|
ui.Error(fmt.Sprintf(
|
2015-06-10 17:02:06 -04:00
|
|
|
"Error destroying droplet. Please destroy it manually: %s", err))
|
2013-06-13 12:48:19 -04:00
|
|
|
}
|
|
|
|
}
|