2020-10-15 10:51:11 -04:00
|
|
|
package communicator
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
2020-12-01 18:30:31 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/communicator/sshkey"
|
2020-11-17 19:31:03 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
|
2020-11-19 14:54:31 -05:00
|
|
|
packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
|
2020-10-15 10:51:11 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// StepSSHKeyGen is a Packer build step that generates SSH key pairs.
|
|
|
|
type StepSSHKeyGen struct {
|
|
|
|
CommConf *Config
|
|
|
|
SSHTemporaryKeyPair
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run executes the Packer build step that generates SSH key pairs.
|
|
|
|
// The key pairs are added to the ssh config
|
|
|
|
func (s *StepSSHKeyGen) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
|
2020-11-19 14:54:31 -05:00
|
|
|
ui := state.Get("ui").(packersdk.Ui)
|
2020-10-15 10:51:11 -04:00
|
|
|
comm := s.CommConf
|
|
|
|
|
|
|
|
if comm.SSHPrivateKeyFile != "" {
|
|
|
|
ui.Say("Using existing SSH private key")
|
|
|
|
privateKeyBytes, err := comm.ReadSSHPrivateKeyFile()
|
|
|
|
if err != nil {
|
|
|
|
state.Put("error", err)
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
comm.SSHPrivateKey = privateKeyBytes
|
|
|
|
comm.SSHPublicKey = nil
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2020-10-21 05:53:07 -04:00
|
|
|
algorithm := s.SSHTemporaryKeyPair.SSHTemporaryKeyPairType
|
2020-10-15 10:51:11 -04:00
|
|
|
if algorithm == "" {
|
2020-10-26 10:45:06 -04:00
|
|
|
algorithm = sshkey.RSA.String()
|
2020-10-15 10:51:11 -04:00
|
|
|
}
|
|
|
|
a, err := sshkey.AlgorithmString(algorithm)
|
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("%w: possible algorithm types are `dsa` | `ecdsa` | `ed25519` | `rsa` ( the default )", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
ui.Say(fmt.Sprintf("Creating temporary %s SSH key for instance...", a.String()))
|
2020-10-21 05:53:07 -04:00
|
|
|
pair, err := sshkey.GeneratePair(a, nil, s.SSHTemporaryKeyPairBits)
|
2020-10-15 10:51:11 -04:00
|
|
|
if err != nil {
|
|
|
|
err := fmt.Errorf("Error creating temporary ssh key: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
ui.Error(err.Error())
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
comm.SSHPrivateKey = pair.Private
|
|
|
|
comm.SSHPublicKey = pair.Public
|
|
|
|
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Nothing to clean up. SSH keys are associated with a single GCE instance.
|
|
|
|
func (s *StepSSHKeyGen) Cleanup(state multistep.StateBag) {}
|