This repository has been archived by the owner on Mar 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstep_create_ssh_key.go
78 lines (63 loc) · 2.28 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
72
73
74
75
76
77
78
package exoscale
import (
"context"
"fmt"
"io/ioutil"
"path/filepath"
"github.com/exoscale/egoscale"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
type stepCreateSSHKey struct{}
func (s *stepCreateSSHKey) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
var (
buildID = state.Get("build-id").(string)
exo = state.Get("exo").(*egoscale.Client)
ui = state.Get("ui").(packer.Ui)
config = state.Get("config").(*Config)
)
// If an instance SSH key is specified, we assume it already exists and that the SSH communicator is
// configured accordingly.
if config.InstanceSSHKey != "" {
return multistep.ActionContinue
}
// No instance SSH key specified: creating a throwaway key and configure the SSH communicator to use it.
ui.Say("Creating SSH key")
config.InstanceSSHKey = "packer-" + buildID
state.Put("delete_ssh_key", true) // Flag the key for deletion once the build is successfully completed.
resp, err := exo.RequestWithContext(ctx, &egoscale.CreateSSHKeyPair{Name: config.InstanceSSHKey})
if err != nil {
ui.Error(fmt.Sprintf("unable to create SSH key: %s", err))
return multistep.ActionHalt
}
sshKey := resp.(*egoscale.SSHKeyPair)
config.Comm.SSHPrivateKey = []byte(sshKey.PrivateKey)
if config.PackerDebug {
sshPrivateKeyFile := config.InstanceSSHKey
if err := ioutil.WriteFile(sshPrivateKeyFile, config.Comm.SSHPrivateKey, 0o600); err != nil {
ui.Error(fmt.Sprintf("unable to write SSH private key to file: %s", err))
return multistep.ActionHalt
}
absPath, err := filepath.Abs(sshPrivateKeyFile)
if err != nil {
ui.Error(fmt.Sprintf("unable to resolve SSH private key file absolute path: %s", err))
return multistep.ActionHalt
}
ui.Message(fmt.Sprintf("SSH private key file: %s", absPath))
}
return multistep.ActionContinue
}
func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) {
var (
exo = state.Get("exo").(*egoscale.Client)
ui = state.Get("ui").(packer.Ui)
config = state.Get("config").(*Config)
)
if state.Get("delete_ssh_key").(bool) {
ui.Say("Cleanup: deleting SSH key")
err := exo.BooleanRequest(&egoscale.DeleteSSHKeyPair{Name: config.InstanceSSHKey})
if err != nil {
ui.Error(fmt.Sprintf("unable to delete SSH key: %s", err))
}
}
}