github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/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  	})
    53  	if err != nil {
    54  		err := fmt.Errorf("Error creating droplet: %s", err)
    55  		state.Put("error", err)
    56  		ui.Error(err.Error())
    57  		return multistep.ActionHalt
    58  	}
    59  
    60  	// We use this in cleanup
    61  	s.dropletId = droplet.ID
    62  
    63  	// Store the droplet id for later
    64  	state.Put("droplet_id", droplet.ID)
    65  
    66  	return multistep.ActionContinue
    67  }
    68  
    69  func (s *stepCreateDroplet) Cleanup(state multistep.StateBag) {
    70  	// If the dropletid isn't there, we probably never created it
    71  	if s.dropletId == 0 {
    72  		return
    73  	}
    74  
    75  	client := state.Get("client").(*godo.Client)
    76  	ui := state.Get("ui").(packer.Ui)
    77  
    78  	// Destroy the droplet we just created
    79  	ui.Say("Destroying droplet...")
    80  	_, err := client.Droplets.Delete(context.TODO(), s.dropletId)
    81  	if err != nil {
    82  		ui.Error(fmt.Sprintf(
    83  			"Error destroying droplet. Please destroy it manually: %s", err))
    84  	}
    85  }