github.phpd.cn/hashicorp/packer@v1.3.2/builder/googlecompute/step_create_ssh_key.go (about) 1 package googlecompute 2 3 import ( 4 "context" 5 "crypto/rand" 6 "crypto/rsa" 7 "crypto/x509" 8 "encoding/pem" 9 "fmt" 10 "io/ioutil" 11 "os" 12 13 "github.com/hashicorp/packer/helper/multistep" 14 "github.com/hashicorp/packer/packer" 15 "golang.org/x/crypto/ssh" 16 ) 17 18 // StepCreateSSHKey represents a Packer build step that generates SSH key pairs. 19 type StepCreateSSHKey struct { 20 Debug bool 21 DebugKeyPath string 22 } 23 24 // Run executes the Packer build step that generates SSH key pairs. 25 // The key pairs are added to the ssh config 26 func (s *StepCreateSSHKey) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 27 ui := state.Get("ui").(packer.Ui) 28 config := state.Get("config").(*Config) 29 30 if config.Comm.SSHPrivateKeyFile != "" { 31 ui.Say("Using existing SSH private key") 32 privateKeyBytes, err := ioutil.ReadFile(config.Comm.SSHPrivateKeyFile) 33 if err != nil { 34 state.Put("error", fmt.Errorf( 35 "Error loading configured private key file: %s", err)) 36 return multistep.ActionHalt 37 } 38 39 config.Comm.SSHPrivateKey = privateKeyBytes 40 config.Comm.SSHPublicKey = nil 41 42 return multistep.ActionContinue 43 } 44 45 ui.Say("Creating temporary SSH key for instance...") 46 priv, err := rsa.GenerateKey(rand.Reader, 2048) 47 if err != nil { 48 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 49 state.Put("error", err) 50 ui.Error(err.Error()) 51 return multistep.ActionHalt 52 } 53 54 priv_blk := pem.Block{ 55 Type: "RSA PRIVATE KEY", 56 Headers: nil, 57 Bytes: x509.MarshalPKCS1PrivateKey(priv), 58 } 59 60 pub, err := ssh.NewPublicKey(&priv.PublicKey) 61 if err != nil { 62 err := fmt.Errorf("Error creating temporary ssh key: %s", err) 63 state.Put("error", err) 64 ui.Error(err.Error()) 65 return multistep.ActionHalt 66 } 67 config.Comm.SSHPrivateKey = pem.EncodeToMemory(&priv_blk) 68 config.Comm.SSHPublicKey = ssh.MarshalAuthorizedKey(pub) 69 70 if s.Debug { 71 ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath)) 72 f, err := os.Create(s.DebugKeyPath) 73 if err != nil { 74 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 75 return multistep.ActionHalt 76 } 77 78 // Write out the key 79 err = pem.Encode(f, &priv_blk) 80 f.Close() 81 if err != nil { 82 state.Put("error", fmt.Errorf("Error saving debug key: %s", err)) 83 return multistep.ActionHalt 84 } 85 } 86 return multistep.ActionContinue 87 } 88 89 // Nothing to clean up. SSH keys are associated with a single GCE instance. 90 func (s *StepCreateSSHKey) Cleanup(state multistep.StateBag) {}