github.com/amanya/packer@v0.12.1-0.20161117214323-902ac5ab2eb6/builder/profitbricks/step_create_ssh_key.go (about) 1 package profitbricks 2 3 import ( 4 "crypto/rand" 5 "crypto/rsa" 6 "crypto/x509" 7 "encoding/pem" 8 "fmt" 9 "os" 10 11 "github.com/mitchellh/multistep" 12 "github.com/mitchellh/packer/packer" 13 "golang.org/x/crypto/ssh" 14 "io/ioutil" 15 ) 16 17 type StepCreateSSHKey struct { 18 Debug bool 19 DebugKeyPath string 20 } 21 22 func (s *StepCreateSSHKey) Run(state multistep.StateBag) multistep.StepAction { 23 ui := state.Get("ui").(packer.Ui) 24 c := state.Get("config").(*Config) 25 26 if c.SSHKey_path == "" { 27 ui.Say("Creating temporary SSH key for instance...") 28 priv, err := rsa.GenerateKey(rand.Reader, 2048) 29 if err != nil { 30 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 31 state.Put("error", err) 32 ui.Error(err.Error()) 33 return multistep.ActionHalt 34 } 35 36 priv_blk := pem.Block{ 37 Type: "RSA PRIVATE KEY", 38 Headers: nil, 39 Bytes: x509.MarshalPKCS1PrivateKey(priv), 40 } 41 42 pub, err := ssh.NewPublicKey(&priv.PublicKey) 43 if err != nil { 44 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 45 state.Put("error", err) 46 ui.Error(err.Error()) 47 return multistep.ActionHalt 48 } 49 state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk))) 50 state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub))) 51 52 ui.Message(fmt.Sprintf("Saving key to: %s", s.DebugKeyPath)) 53 f, err := os.Create(s.DebugKeyPath) 54 if err != nil { 55 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 56 return multistep.ActionHalt 57 } 58 59 f.Chmod(os.FileMode(int(0700))) 60 err = pem.Encode(f, &priv_blk) 61 f.Close() 62 if err != nil { 63 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 64 return multistep.ActionHalt 65 } 66 } else { 67 ui.Say(c.SSHKey_path) 68 pemBytes, err := ioutil.ReadFile(c.SSHKey_path) 69 70 if err != nil { 71 ui.Error(err.Error()) 72 return multistep.ActionHalt 73 } 74 75 block, _ := pem.Decode(pemBytes) 76 77 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) 78 79 if err != nil { 80 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 81 state.Put("error", err) 82 ui.Error(err.Error()) 83 return multistep.ActionHalt 84 } 85 86 priv_blk := pem.Block{ 87 Type: "RSA PRIVATE KEY", 88 Headers: nil, 89 Bytes: x509.MarshalPKCS1PrivateKey(priv), 90 } 91 92 pub, err := ssh.NewPublicKey(&priv.PublicKey) 93 if err != nil { 94 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 95 state.Put("error", err) 96 ui.Error(err.Error()) 97 return multistep.ActionHalt 98 } 99 state.Put("privateKey", string(pem.EncodeToMemory(&priv_blk))) 100 state.Put("publicKey", string(ssh.MarshalAuthorizedKey(pub))) 101 } 102 return multistep.ActionContinue 103 } 104 105 func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}