github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/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  	"log"
    10  	"time"
    11  )
    12  
    13  type stepCreateDroplet struct {
    14  	dropletId uint
    15  }
    16  
    17  func (s *stepCreateDroplet) Run(state map[string]interface{}) multistep.StepAction {
    18  	client := state["client"].(*DigitalOceanClient)
    19  	ui := state["ui"].(packer.Ui)
    20  	c := state["config"].(config)
    21  	sshKeyId := state["ssh_key_id"].(uint)
    22  
    23  	ui.Say("Creating droplet...")
    24  
    25  	// Some random droplet name as it's temporary
    26  	name := fmt.Sprintf("packer-%s", hex.EncodeToString(identifier.NewUUID().Raw()))
    27  
    28  	// Create the droplet based on configuration
    29  	dropletId, err := client.CreateDroplet(name, c.SizeID, c.ImageID, c.RegionID, sshKeyId)
    30  	if err != nil {
    31  		err := fmt.Errorf("Error creating droplet: %s", err)
    32  		state["error"] = err
    33  		ui.Error(err.Error())
    34  		return multistep.ActionHalt
    35  	}
    36  
    37  	// We use this in cleanup
    38  	s.dropletId = dropletId
    39  
    40  	// Store the droplet id for later
    41  	state["droplet_id"] = dropletId
    42  
    43  	return multistep.ActionContinue
    44  }
    45  
    46  func (s *stepCreateDroplet) Cleanup(state map[string]interface{}) {
    47  	// If the dropletid isn't there, we probably never created it
    48  	if s.dropletId == 0 {
    49  		return
    50  	}
    51  
    52  	client := state["client"].(*DigitalOceanClient)
    53  	ui := state["ui"].(packer.Ui)
    54  	c := state["config"].(config)
    55  
    56  	// Destroy the droplet we just created
    57  	ui.Say("Destroying droplet...")
    58  
    59  	// Sleep arbitrarily before sending destroy request
    60  	// Otherwise we get "pending event" errors, even though there isn't
    61  	// one.
    62  	log.Printf("Sleeping for %v, event_delay", c.RawEventDelay)
    63  	time.Sleep(c.eventDelay)
    64  
    65  	err := client.DestroyDroplet(s.dropletId)
    66  
    67  	curlstr := fmt.Sprintf("curl '%v/droplets/%v/destroy?client_id=%v&api_key=%v'",
    68  		DIGITALOCEAN_API_URL, s.dropletId, c.ClientID, c.APIKey)
    69  
    70  	if err != nil {
    71  		ui.Error(fmt.Sprintf(
    72  			"Error destroying droplet. Please destroy it manually: %v", curlstr))
    73  	}
    74  }