github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/oneandone/step_create_sshkey.go (about) 1 package oneandone 2 3 import ( 4 "crypto/x509" 5 "encoding/pem" 6 "fmt" 7 "github.com/mitchellh/multistep" 8 "github.com/mitchellh/packer/packer" 9 "golang.org/x/crypto/ssh" 10 "io/ioutil" 11 ) 12 13 type StepCreateSSHKey struct { 14 Debug bool 15 DebugKeyPath string 16 } 17 18 func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction { 19 ui := state.Get("ui").(packer.Ui) 20 c := state.Get("config").(*Config) 21 22 if c.Comm.SSHPrivateKey != "" { 23 pemBytes, err := ioutil.ReadFile(c.Comm.SSHPrivateKey) 24 25 if err != nil { 26 ui.Error(err.Error()) 27 return multistep.ActionHalt 28 } 29 30 block, _ := pem.Decode(pemBytes) 31 32 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) 33 34 if err != nil { 35 36 state.Put("error", err.Error()) 37 ui.Error(err.Error()) 38 return multistep.ActionHalt 39 } 40 41 priv_blk := pem.Block{ 42 Type: "RSA PRIVATE KEY", 43 Headers: nil, 44 Bytes: x509.MarshalPKCS1PrivateKey(priv), 45 } 46 47 pub, err := ssh.NewPublicKey(&priv.PublicKey) 48 if err != nil { 49 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 50 state.Put("error", err) 51 ui.Error(err.Error()) 52 return multistep.ActionHalt 53 } 54 state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk))) 55 state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub))) 56 } 57 return multistep.ActionContinue 58 } 59 60 func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}