packer-cn/builder/yandex/step_create_ssh_key.go

101 lines
2.7 KiB
Go
Raw Normal View History

2019-03-26 08:29:15 -04:00
package yandex
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"golang.org/x/crypto/ssh"
)
type stepCreateSSHKey struct {
Debug bool
DebugKeyPath string
}
func (s *stepCreateSSHKey) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
config := state.Get("config").(*Config)
2019-03-26 08:29:15 -04:00
if config.Communicator.SSHPrivateKeyFile != "" {
2019-03-26 08:29:15 -04:00
ui.Say("Using existing SSH private key")
privateKeyBytes, err := config.Communicator.ReadSSHPrivateKeyFile()
2019-03-26 08:29:15 -04:00
if err != nil {
state.Put("error", err)
return multistep.ActionHalt
}
key, err := ssh.ParsePrivateKey(privateKeyBytes)
if err != nil {
err = fmt.Errorf("Error parsing 'ssh_private_key_file': %s", err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
config.Communicator.SSHPublicKey = ssh.MarshalAuthorizedKey(key.PublicKey())
config.Communicator.SSHPrivateKey = privateKeyBytes
2019-03-26 08:29:15 -04:00
return multistep.ActionContinue
}
ui.Say("Creating temporary ssh key for instance...")
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return stepHaltWithError(state, fmt.Errorf("Error generating temporary SSH key: %s", err))
}
// ASN.1 DER encoded form
privDer := x509.MarshalPKCS1PrivateKey(priv)
privBlk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDer,
}
// Marshal the public key into SSH compatible format
pub, err := ssh.NewPublicKey(&priv.PublicKey)
if err != nil {
err = fmt.Errorf("Error creating public ssh key: %s", err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
2019-03-26 08:29:15 -04:00
pubSSHFormat := string(ssh.MarshalAuthorizedKey(pub))
hashMD5 := ssh.FingerprintLegacyMD5(pub)
hashSHA256 := ssh.FingerprintSHA256(pub)
2019-03-26 08:29:15 -04:00
log.Printf("[INFO] md5 hash of ssh pub key: %s", hashMD5)
log.Printf("[INFO] sha256 hash of ssh pub key: %s", hashSHA256)
2019-03-26 08:29:15 -04:00
// Remember some state for the future
state.Put("ssh_key_public", pubSSHFormat)
// Set the private key in the config for later
config.Communicator.SSHPrivateKey = pem.EncodeToMemory(&privBlk)
config.Communicator.SSHPublicKey = ssh.MarshalAuthorizedKey(pub)
2019-03-26 08:29:15 -04:00
// If we're in debug mode, output the private key to the working directory.
if s.Debug {
ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath))
err := ioutil.WriteFile(s.DebugKeyPath, config.Communicator.SSHPrivateKey, 0600)
2019-03-26 08:29:15 -04:00
if err != nil {
return stepHaltWithError(state, fmt.Errorf("Error saving debug key: %s", err))
}
}
return multistep.ActionContinue
}
func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) {
}