github.com/daniellockard/packer@v0.7.6-0.20141210173435-5a9390934716/builder/digitalocean/step_create_ssh_key.go (about) 1 package digitalocean 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/x509" 7 "encoding/pem" 8 "fmt" 9 "log" 10 11 "code.google.com/p/gosshold/ssh" 12 "github.com/mitchellh/multistep" 13 "github.com/mitchellh/packer/common/uuid" 14 "github.com/mitchellh/packer/packer" 15 ) 16 17 type stepCreateSSHKey struct { 18 keyId uint 19 } 20 21 func (s *stepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction { 22 client := state.Get("client").(DigitalOceanClient) 23 ui := state.Get("ui").(packer.Ui) 24 25 ui.Say("Creating temporary ssh key for droplet...") 26 27 priv, err := rsa.GenerateKey(rand.Reader, 2014) 28 29 // ASN.1 DER encoded form 30 priv_der := x509.MarshalPKCS1PrivateKey(priv) 31 priv_blk := pem.Block{ 32 Type: "RSA PRIVATE KEY", 33 Headers: nil, 34 Bytes: priv_der, 35 } 36 37 // Set the private key in the statebag for later 38 state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk))) 39 40 // Marshal the public key into SSH compatible format 41 // TODO properly handle the public key error 42 pub, _ := ssh.NewPublicKey(&priv.PublicKey) 43 pub_sshformat := string(ssh.MarshalAuthorizedKey(pub)) 44 45 // The name of the public key on DO 46 name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID()) 47 48 // Create the key! 49 keyId, err := client.CreateKey(name, pub_sshformat) 50 if err != nil { 51 err := fmt.Errorf("Error creating temporary SSH key: %s", err) 52 state.Put("error", err) 53 ui.Error(err.Error()) 54 return multistep.ActionHalt 55 } 56 57 // We use this to check cleanup 58 s.keyId = keyId 59 60 log.Printf("temporary ssh key name: %s", name) 61 62 // Remember some state for the future 63 state.Put("ssh_key_id", keyId) 64 65 return multistep.ActionContinue 66 } 67 68 func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) { 69 // If no key name is set, then we never created it, so just return 70 if s.keyId == 0 { 71 return 72 } 73 74 client := state.Get("client").(DigitalOceanClient) 75 ui := state.Get("ui").(packer.Ui) 76 c := state.Get("config").(config) 77 78 ui.Say("Deleting temporary ssh key...") 79 err := client.DestroyKey(s.keyId) 80 81 curlstr := fmt.Sprintf("curl -H 'Authorization: Bearer #TOKEN#' -X DELETE '%v/v2/account/keys/%v'", c.APIURL, s.keyId) 82 83 if err != nil { 84 log.Printf("Error cleaning up ssh key: %v", err.Error()) 85 ui.Error(fmt.Sprintf( 86 "Error cleaning up ssh key. Please delete the key manually: %v", curlstr)) 87 } 88 }