github.com/alouche/packer@v0.3.7/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 pub := priv.PublicKey 42 pub_sshformat := string(ssh.MarshalAuthorizedKey(&pub)) 43 44 // The name of the public key on DO 45 name := fmt.Sprintf("packer-%s", hex.EncodeToString(identifier.NewUUID().Raw())) 46 47 // Create the key! 48 keyId, err := client.CreateKey(name, pub_sshformat) 49 if err != nil { 50 err := fmt.Errorf("Error creating temporary SSH key: %s", err) 51 state.Put("error", err) 52 ui.Error(err.Error()) 53 return multistep.ActionHalt 54 } 55 56 // We use this to check cleanup 57 s.keyId = keyId 58 59 log.Printf("temporary ssh key name: %s", name) 60 61 // Remember some state for the future 62 state.Put("ssh_key_id", keyId) 63 64 return multistep.ActionContinue 65 } 66 67 func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) { 68 // If no key name is set, then we never created it, so just return 69 if s.keyId == 0 { 70 return 71 } 72 73 client := state.Get("client").(*DigitalOceanClient) 74 ui := state.Get("ui").(packer.Ui) 75 c := state.Get("config").(config) 76 77 ui.Say("Deleting temporary ssh key...") 78 err := client.DestroyKey(s.keyId) 79 80 curlstr := fmt.Sprintf("curl '%v/ssh_keys/%v/destroy?client_id=%v&api_key=%v'", 81 DIGITALOCEAN_API_URL, s.keyId, c.ClientID, c.APIKey) 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 }