2013-06-13 12:48:19 -04:00
|
|
|
package digitalocean
|
|
|
|
|
|
|
|
import (
|
|
|
|
"cgl.tideland.biz/identifier"
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
"github.com/mitchellh/multistep"
|
|
|
|
"github.com/mitchellh/packer/packer"
|
2013-06-17 07:28:21 -04:00
|
|
|
"log"
|
2013-06-14 09:26:03 -04:00
|
|
|
"time"
|
2013-06-13 12:48:19 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type stepCreateDroplet struct {
|
|
|
|
dropletId uint
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *stepCreateDroplet) Run(state map[string]interface{}) multistep.StepAction {
|
|
|
|
client := state["client"].(*DigitalOceanClient)
|
|
|
|
ui := state["ui"].(packer.Ui)
|
|
|
|
c := state["config"].(config)
|
|
|
|
sshKeyId := state["ssh_key_id"].(uint)
|
|
|
|
|
|
|
|
ui.Say("Creating droplet...")
|
|
|
|
|
|
|
|
// Some random droplet name as it's temporary
|
|
|
|
name := fmt.Sprintf("packer-%s", hex.EncodeToString(identifier.NewUUID().Raw()))
|
|
|
|
|
|
|
|
// Create the droplet based on configuration
|
|
|
|
dropletId, err := client.CreateDroplet(name, c.SizeID, c.ImageID, c.RegionID, sshKeyId)
|
|
|
|
if err != nil {
|
2013-06-20 00:00:51 -04:00
|
|
|
err := fmt.Errorf("Error creating droplet: %s", err)
|
|
|
|
state["error"] = err
|
2013-06-13 12:48:19 -04:00
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
// We use this in cleanup
|
|
|
|
s.dropletId = dropletId
|
|
|
|
|
|
|
|
// Store the droplet id for later
|
|
|
|
state["droplet_id"] = dropletId
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *stepCreateDroplet) Cleanup(state map[string]interface{}) {
|
|
|
|
// If the dropletid isn't there, we probably never created it
|
|
|
|
if s.dropletId == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
client := state["client"].(*DigitalOceanClient)
|
|
|
|
ui := state["ui"].(packer.Ui)
|
2013-06-17 07:28:21 -04:00
|
|
|
c := state["config"].(config)
|
2013-06-13 12:48:19 -04:00
|
|
|
|
|
|
|
// Destroy the droplet we just created
|
|
|
|
ui.Say("Destroying droplet...")
|
2013-06-14 09:26:03 -04:00
|
|
|
|
|
|
|
// Sleep arbitrarily before sending destroy request
|
|
|
|
// Otherwise we get "pending event" errors, even though there isn't
|
|
|
|
// one.
|
2013-06-17 07:28:21 -04:00
|
|
|
log.Printf("Sleeping for %v, event_delay", c.RawEventDelay)
|
2013-07-14 08:20:29 -04:00
|
|
|
time.Sleep(c.eventDelay)
|
2013-06-14 09:26:03 -04:00
|
|
|
|
2013-06-13 12:48:19 -04:00
|
|
|
err := client.DestroyDroplet(s.dropletId)
|
|
|
|
|
2013-06-17 08:22:29 -04:00
|
|
|
curlstr := fmt.Sprintf("curl '%v/droplets/%v/destroy?client_id=%v&api_key=%v'",
|
|
|
|
DIGITALOCEAN_API_URL, s.dropletId, c.ClientID, c.APIKey)
|
|
|
|
|
2013-06-13 12:48:19 -04:00
|
|
|
if err != nil {
|
|
|
|
ui.Error(fmt.Sprintf(
|
2013-06-17 08:22:29 -04:00
|
|
|
"Error destroying droplet. Please destroy it manually: %v", curlstr))
|
2013-06-13 12:48:19 -04:00
|
|
|
}
|
|
|
|
}
|