packer-cn/builder/oracle/classic/step_add_keys.go

60 lines
1.7 KiB
Go
Raw Normal View History

2018-01-22 19:54:49 -05:00
package classic
import (
2018-01-25 17:43:55 -05:00
"context"
2018-01-22 19:54:49 -05:00
"fmt"
"strings"
"github.com/hashicorp/go-oracle-terraform/compute"
2018-01-25 17:45:09 -05:00
"github.com/hashicorp/packer/helper/multistep"
2018-01-22 19:54:49 -05:00
"github.com/hashicorp/packer/packer"
)
type stepAddKeysToAPI struct{}
2018-01-25 17:42:39 -05:00
func (s *stepAddKeysToAPI) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
2018-01-22 19:54:49 -05:00
// get variables from state
ui := state.Get("ui").(packer.Ui)
ui.Say("Adding SSH keys to API...")
config := state.Get("config").(*Config)
client := state.Get("client").(*compute.ComputeClient)
// grab packer-generated key from statebag context.
sshPublicKey := strings.TrimSpace(state.Get("publicKey").(string))
// form API call to add key to compute cloud
sshKeyName := fmt.Sprintf("/Compute-%s/%s/packer_generated_key", config.IdentityDomain, config.Username)
sshKeysClient := client.SSHKeys()
sshKeysInput := compute.CreateSSHKeyInput{
Name: sshKeyName,
Key: sshPublicKey,
Enabled: true,
}
// Load the packer-generated SSH key into the Oracle Compute cloud.
keyInfo, err := sshKeysClient.CreateSSHKey(&sshKeysInput)
if err != nil {
// Key already exists; update key instead of creating it
if strings.Contains(err.Error(), "packer_generated_key already exists") {
updateKeysInput := compute.UpdateSSHKeyInput{
Name: sshKeyName,
Key: sshPublicKey,
Enabled: true,
}
keyInfo, err = sshKeysClient.UpdateSSHKey(&updateKeysInput)
} else {
err = fmt.Errorf("Problem adding Public SSH key through Oracle's API: %s", err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
}
state.Put("key_name", keyInfo.Name)
return multistep.ActionContinue
}
func (s *stepAddKeysToAPI) Cleanup(state multistep.StateBag) {
// Nothing to do
}