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