github.com/amanya/packer@v0.12.1-0.20161117214323-902ac5ab2eb6/builder/digitalocean/step_create_droplet.go (about) 1 package digitalocean 2 3 import ( 4 "fmt" 5 6 "github.com/digitalocean/godo" 7 "github.com/mitchellh/multistep" 8 "github.com/mitchellh/packer/packer" 9 "io/ioutil" 10 ) 11 12 type stepCreateDroplet struct { 13 dropletId int 14 } 15 16 func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction { 17 client := state.Get("client").(*godo.Client) 18 ui := state.Get("ui").(packer.Ui) 19 c := state.Get("config").(Config) 20 sshKeyId := state.Get("ssh_key_id").(int) 21 22 // Create the droplet based on configuration 23 ui.Say("Creating droplet...") 24 25 userData := c.UserData 26 if c.UserDataFile != "" { 27 contents, err := ioutil.ReadFile(c.UserDataFile) 28 if err != nil { 29 state.Put("error", fmt.Errorf("Problem reading user data file: %s", err)) 30 return multistep.ActionHalt 31 } 32 33 userData = string(contents) 34 } 35 36 droplet, _, err := client.Droplets.Create(&godo.DropletCreateRequest{ 37 Name: c.DropletName, 38 Region: c.Region, 39 Size: c.Size, 40 Image: godo.DropletCreateImage{ 41 Slug: c.Image, 42 }, 43 SSHKeys: []godo.DropletCreateSSHKey{ 44 {ID: int(sshKeyId)}, 45 }, 46 PrivateNetworking: c.PrivateNetworking, 47 UserData: userData, 48 }) 49 if err != nil { 50 err := fmt.Errorf("Error creating droplet: %s", err) 51 state.Put("error", err) 52 ui.Error(err.Error()) 53 return multistep.ActionHalt 54 } 55 56 // We use this in cleanup 57 s.dropletId = droplet.ID 58 59 // Store the droplet id for later 60 state.Put("droplet_id", droplet.ID) 61 62 return multistep.ActionContinue 63 } 64 65 func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) { 66 // If the dropletid isn't there, we probably never created it 67 if s.dropletId == 0 { 68 return 69 } 70 71 client := state.Get("client").(*godo.Client) 72 ui := state.Get("ui").(packer.Ui) 73 74 // Destroy the droplet we just created 75 ui.Say("Destroying droplet...") 76 _, err := client.Droplets.Delete(s.dropletId) 77 if err != nil { 78 ui.Error(fmt.Sprintf( 79 "Error destroying droplet. Please destroy it manually: %s", err)) 80 } 81 }