github.com/jerryclinesmith/packer@v0.3.7/builder/digitalocean/step_create_droplet.go (about) 1 package digitalocean 2 3 import ( 4 "cgl.tideland.biz/identifier" 5 "encoding/hex" 6 "fmt" 7 "github.com/mitchellh/multistep" 8 "github.com/mitchellh/packer/packer" 9 ) 10 11 type stepCreateDroplet struct { 12 dropletId uint 13 } 14 15 func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction { 16 client := state.Get("client").(*DigitalOceanClient) 17 ui := state.Get("ui").(packer.Ui) 18 c := state.Get("config").(config) 19 sshKeyId := state.Get("ssh_key_id").(uint) 20 21 ui.Say("Creating droplet...") 22 23 // Some random droplet name as it's temporary 24 name := fmt.Sprintf("packer-%s", hex.EncodeToString(identifier.NewUUID().Raw())) 25 26 // Create the droplet based on configuration 27 dropletId, err := client.CreateDroplet(name, c.SizeID, c.ImageID, c.RegionID, sshKeyId) 28 if err != nil { 29 err := fmt.Errorf("Error creating droplet: %s", err) 30 state.Put("error", err) 31 ui.Error(err.Error()) 32 return multistep.ActionHalt 33 } 34 35 // We use this in cleanup 36 s.dropletId = dropletId 37 38 // Store the droplet id for later 39 state.Put("droplet_id", dropletId) 40 41 return multistep.ActionContinue 42 } 43 44 func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) { 45 // If the dropletid isn't there, we probably never created it 46 if s.dropletId == 0 { 47 return 48 } 49 50 client := state.Get("client").(*DigitalOceanClient) 51 ui := state.Get("ui").(packer.Ui) 52 c := state.Get("config").(config) 53 54 // Destroy the droplet we just created 55 ui.Say("Destroying droplet...") 56 57 err := client.DestroyDroplet(s.dropletId) 58 if err != nil { 59 curlstr := fmt.Sprintf("curl '%v/droplets/%v/destroy?client_id=%v&api_key=%v'", 60 DIGITALOCEAN_API_URL, s.dropletId, c.ClientID, c.APIKey) 61 62 ui.Error(fmt.Sprintf( 63 "Error destroying droplet. Please destroy it manually: %v", curlstr)) 64 } 65 }