github.com/kaixiang/packer@v0.5.2-0.20140114230416-1f5786b0d7f1/builder/googlecompute/step_create_ssh_key.go (about) 1 package googlecompute 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/x509" 7 "encoding/pem" 8 "fmt" 9 10 "code.google.com/p/go.crypto/ssh" 11 "github.com/mitchellh/multistep" 12 "github.com/mitchellh/packer/packer" 13 ) 14 15 // StepCreateSSHKey represents a Packer build step that generates SSH key pairs. 16 type StepCreateSSHKey int 17 18 // Run executes the Packer build step that generates SSH key pairs. 19 func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction { 20 ui := state.Get("ui").(packer.Ui) 21 22 ui.Say("Creating temporary SSH key for instance...") 23 priv, err := rsa.GenerateKey(rand.Reader, 2048) 24 if err != nil { 25 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 26 state.Put("error", err) 27 ui.Error(err.Error()) 28 return multistep.ActionHalt 29 } 30 31 priv_blk := pem.Block{ 32 Type: "RSA PRIVATE KEY", 33 Headers: nil, 34 Bytes: x509.MarshalPKCS1PrivateKey(priv), 35 } 36 37 pub, err := ssh.NewPublicKey(&priv.PublicKey) 38 if err != nil { 39 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 40 state.Put("error", err) 41 ui.Error(err.Error()) 42 return multistep.ActionHalt 43 } 44 45 state.Put("ssh_private_key", string(pem.EncodeToMemory(&priv_blk))) 46 state.Put("ssh_public_key", string(ssh.MarshalAuthorizedKey(pub))) 47 return multistep.ActionContinue 48 } 49 50 // Nothing to clean up. SSH keys are associated with a single GCE instance. 51 func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}