github.com/rothwerx/packer@v0.9.0/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  )
    10  
    11  type stepCreateDroplet struct {
    12  	dropletId int
    13  }
    14  
    15  func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction {
    16  	client := state.Get("client").(*godo.Client)
    17  	ui := state.Get("ui").(packer.Ui)
    18  	c := state.Get("config").(Config)
    19  	sshKeyId := state.Get("ssh_key_id").(int)
    20  
    21  	// Create the droplet based on configuration
    22  	ui.Say("Creating droplet...")
    23  	droplet, _, err := client.Droplets.Create(&godo.DropletCreateRequest{
    24  		Name:   c.DropletName,
    25  		Region: c.Region,
    26  		Size:   c.Size,
    27  		Image: godo.DropletCreateImage{
    28  			Slug: c.Image,
    29  		},
    30  		SSHKeys: []godo.DropletCreateSSHKey{
    31  			godo.DropletCreateSSHKey{ID: int(sshKeyId)},
    32  		},
    33  		PrivateNetworking: c.PrivateNetworking,
    34  		UserData:          c.UserData,
    35  	})
    36  	if err != nil {
    37  		err := fmt.Errorf("Error creating droplet: %s", err)
    38  		state.Put("error", err)
    39  		ui.Error(err.Error())
    40  		return multistep.ActionHalt
    41  	}
    42  
    43  	// We use this in cleanup
    44  	s.dropletId = droplet.ID
    45  
    46  	// Store the droplet id for later
    47  	state.Put("droplet_id", droplet.ID)
    48  
    49  	return multistep.ActionContinue
    50  }
    51  
    52  func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) {
    53  	// If the dropletid isn't there, we probably never created it
    54  	if s.dropletId == 0 {
    55  		return
    56  	}
    57  
    58  	client := state.Get("client").(*godo.Client)
    59  	ui := state.Get("ui").(packer.Ui)
    60  
    61  	// Destroy the droplet we just created
    62  	ui.Say("Destroying droplet...")
    63  	_, err := client.Droplets.Delete(s.dropletId)
    64  	if err != nil {
    65  		ui.Error(fmt.Sprintf(
    66  			"Error destroying droplet. Please destroy it manually: %s", err))
    67  	}
    68  }