/
step_create_ssh_key.go
71 lines (56 loc) · 1.79 KB
/
step_create_ssh_key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package p2pub
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
"golang.org/x/crypto/ssh"
)
type stepCreateSSHKey struct {
}
func (s *stepCreateSSHKey) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
config := state.Get("config").(*Config)
// Using existing key.
if config.Comm.SSHPrivateKeyFile != "" {
ui.Say(fmt.Sprintf("Using existing SSH key: %s", config.Comm.SSHPrivateKeyFile))
privateKeyBytes, err := config.Comm.ReadSSHPrivateKeyFile()
if err != nil {
ui.Error(fmt.Sprintf("Error reading ssh key. reason: %s", err.Error()))
state.Put("error", err)
return multistep.ActionHalt
}
config.Comm.SSHPrivateKey = privateKeyBytes
config.Comm.SSHPublicKey = nil
return multistep.ActionContinue
}
// Using temporary key and connect as "root"
ui.Say(fmt.Sprintf("Creating temporary SSH key pair ..."))
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
ui.Error(fmt.Sprintf("Error creating temporary ssh key. reason: %s", err.Error()))
state.Put("error", err)
return multistep.ActionHalt
}
privBlk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}
pub, err := ssh.NewPublicKey(&priv.PublicKey)
if err != nil {
ui.Error(fmt.Sprintf("Error creating temporary ssh key. reason: %s", err.Error()))
state.Put("error", err)
return multistep.ActionHalt
}
config.Comm.SSHPrivateKey = pem.EncodeToMemory(&privBlk)
config.Comm.SSHPublicKey = ssh.MarshalAuthorizedKey(pub)
config.RootSSHKey = string(config.Comm.SSHPublicKey)
return multistep.ActionContinue
}
func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) {
}