github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/builder/openstack/step_key_pair.go (about) 1 package openstack 2 3 import ( 4 "fmt" 5 "github.com/mitchellh/multistep" 6 "github.com/mitchellh/packer/common/uuid" 7 "github.com/mitchellh/packer/packer" 8 "github.com/rackspace/gophercloud" 9 "log" 10 "os" 11 "runtime" 12 ) 13 14 type StepKeyPair struct { 15 Debug bool 16 DebugKeyPath string 17 keyName string 18 } 19 20 func (s *StepKeyPair) Run(state multistep.StateBag) multistep.StepAction { 21 csp := state.Get("csp").(gophercloud.CloudServersProvider) 22 ui := state.Get("ui").(packer.Ui) 23 24 ui.Say("Creating temporary keypair for this instance...") 25 keyName := fmt.Sprintf("packer %s", uuid.TimeOrderedUUID()) 26 log.Printf("temporary keypair name: %s", keyName) 27 keyResp, err := csp.CreateKeyPair(gophercloud.NewKeyPair{Name: keyName}) 28 if err != nil { 29 state.Put("error", fmt.Errorf("Error creating temporary keypair: %s", err)) 30 return multistep.ActionHalt 31 } 32 if keyResp.PrivateKey == "" { 33 state.Put("error", fmt.Errorf("The temporary keypair returned was blank")) 34 return multistep.ActionHalt 35 } 36 37 // If we're in debug mode, output the private key to the working 38 // directory. 39 if s.Debug { 40 ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath)) 41 f, err := os.Create(s.DebugKeyPath) 42 if err != nil { 43 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 44 return multistep.ActionHalt 45 } 46 defer f.Close() 47 48 // Write the key out 49 if _, err := f.Write([]byte(keyResp.PrivateKey)); err != nil { 50 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 51 return multistep.ActionHalt 52 } 53 54 // Chmod it so that it is SSH ready 55 if runtime.GOOS != "windows" { 56 if err := f.Chmod(0600); err != nil { 57 state.Put("error", fmt.Errorf("Error setting permissions of debug key: %s", err)) 58 return multistep.ActionHalt 59 } 60 } 61 } 62 63 // Set the keyname so we know to delete it later 64 s.keyName = keyName 65 66 // Set some state data for use in future steps 67 state.Put("keyPair", keyName) 68 state.Put("privateKey", keyResp.PrivateKey) 69 70 return multistep.ActionContinue 71 } 72 73 func (s *StepKeyPair) Cleanup(state multistep.StateBag) { 74 // If no key name is set, then we never created it, so just return 75 if s.keyName == "" { 76 return 77 } 78 79 csp := state.Get("csp").(gophercloud.CloudServersProvider) 80 ui := state.Get("ui").(packer.Ui) 81 82 ui.Say("Deleting temporary keypair...") 83 err := csp.DeleteKeyPair(s.keyName) 84 if err != nil { 85 ui.Error(fmt.Sprintf( 86 "Error cleaning up keypair. Please delete the key manually: %s", s.keyName)) 87 } 88 }