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