github.com/supr/packer@v0.3.10-0.20131015195147-7b09e24ac3c1/builder/digitalocean/step_create_ssh_key.go (about) 1 package digitalocean 2 3 import ( 4 "cgl.tideland.biz/identifier" 5 "code.google.com/p/go.crypto/ssh" 6 "crypto/rand" 7 "crypto/rsa" 8 "crypto/x509" 9 "encoding/hex" 10 "encoding/pem" 11 "fmt" 12 "github.com/mitchellh/multistep" 13 "github.com/mitchellh/packer/packer" 14 "log" 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", hex.EncodeToString(identifier.NewUUID().Raw())) 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 '%v/ssh_keys/%v/destroy?client_id=%v&api_key=%v'", 82 DIGITALOCEAN_API_URL, s.keyId, c.ClientID, c.APIKey) 83 84 if err != nil { 85 log.Printf("Error cleaning up ssh key: %v", err.Error()) 86 ui.Error(fmt.Sprintf( 87 "Error cleaning up ssh key. Please delete the key manually: %v", curlstr)) 88 } 89 }