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

72 lines
2.1 KiB
Go
Raw Normal View History

2018-01-22 19:54:49 -05:00
package classic
import (
"bytes"
2018-01-25 17:43:55 -05:00
"context"
2018-01-22 19:54:49 -05:00
"fmt"
"github.com/hashicorp/go-oracle-terraform/compute"
"github.com/hashicorp/packer/common/uuid"
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)
config := state.Get("config").(*Config)
2018-10-24 17:08:11 -04:00
client := state.Get("client").(*compute.Client)
2018-01-22 19:54:49 -05:00
if config.Comm.Type != "ssh" {
ui.Say("Not using SSH communicator; skip generating SSH keys...")
return multistep.ActionContinue
}
2018-01-22 19:54:49 -05:00
// grab packer-generated key from statebag context.
sshPublicKey := bytes.TrimSpace(config.Comm.SSHPublicKey)
2018-01-22 19:54:49 -05:00
// form API call to add key to compute cloud
2018-09-06 01:44:31 -04:00
sshKeyName := config.Identifier(fmt.Sprintf("packer_generated_key_%s", uuid.TimeOrderedUUID()))
2018-01-22 19:54:49 -05:00
2018-01-26 16:12:35 -05:00
ui.Say(fmt.Sprintf("Creating temporary key: %s", sshKeyName))
2018-01-22 19:54:49 -05:00
sshKeysClient := client.SSHKeys()
sshKeysInput := compute.CreateSSHKeyInput{
Name: sshKeyName,
Key: string(sshPublicKey),
2018-01-22 19:54:49 -05:00
Enabled: true,
}
// Load the packer-generated SSH key into the Oracle Compute cloud.
keyInfo, err := sshKeysClient.CreateSSHKey(&sshKeysInput)
if err != nil {
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
2018-01-22 19:54:49 -05:00
}
config.Comm.SSHKeyPairName = keyInfo.Name
2018-01-22 19:54:49 -05:00
return multistep.ActionContinue
}
func (s *stepAddKeysToAPI) Cleanup(state multistep.StateBag) {
// Delete the keys we created during this run
config := state.Get("config").(*Config)
if len(config.Comm.SSHKeyPairName) == 0 {
// No keys were generated; none need to be cleaned up.
return
}
ui := state.Get("ui").(packer.Ui)
ui.Say("Deleting SSH keys...")
deleteInput := compute.DeleteSSHKeyInput{Name: config.Comm.SSHKeyPairName}
2018-10-24 17:08:11 -04:00
client := state.Get("client").(*compute.Client)
deleteClient := client.SSHKeys()
err := deleteClient.DeleteSSHKey(&deleteInput)
if err != nil {
ui.Error(fmt.Sprintf("Error deleting SSH keys: %s", err.Error()))
}
return
2018-01-22 19:54:49 -05:00
}