github.com/jerryclinesmith/packer@v0.3.7/builder/openstack/step_key_pair.go (about)

     1  package openstack
     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  	"github.com/rackspace/gophercloud"
    10  	"log"
    11  )
    12  
    13  type StepKeyPair struct {
    14  	keyName string
    15  }
    16  
    17  func (s *StepKeyPair) Run(state multistep.StateBag) multistep.StepAction {
    18  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    19  	ui := state.Get("ui").(packer.Ui)
    20  
    21  	ui.Say("Creating temporary keypair for this instance...")
    22  	keyName := fmt.Sprintf("packer %s", hex.EncodeToString(identifier.NewUUID().Raw()))
    23  	log.Printf("temporary keypair name: %s", keyName)
    24  	keyResp, err := csp.CreateKeyPair(gophercloud.NewKeyPair{Name: keyName})
    25  	if err != nil {
    26  		state.Put("error", fmt.Errorf("Error creating temporary keypair: %s", err))
    27  		return multistep.ActionHalt
    28  	}
    29  
    30  	// Set the keyname so we know to delete it later
    31  	s.keyName = keyName
    32  
    33  	// Set some state data for use in future steps
    34  	state.Put("keyPair", keyName)
    35  	state.Put("privateKey", keyResp.PrivateKey)
    36  
    37  	return multistep.ActionContinue
    38  }
    39  
    40  func (s *StepKeyPair) Cleanup(state multistep.StateBag) {
    41  	// If no key name is set, then we never created it, so just return
    42  	if s.keyName == "" {
    43  		return
    44  	}
    45  
    46  	csp := state.Get("csp").(gophercloud.CloudServersProvider)
    47  	ui := state.Get("ui").(packer.Ui)
    48  
    49  	ui.Say("Deleting temporary keypair...")
    50  	err := csp.DeleteKeyPair(s.keyName)
    51  	if err != nil {
    52  		ui.Error(fmt.Sprintf(
    53  			"Error cleaning up keypair. Please delete the key manually: %s", s.keyName))
    54  	}
    55  }