github.phpd.cn/hashicorp/packer@v1.3.2/builder/oracle/classic/step_add_keys.go (about)

     1  package classic
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  
     8  	"github.com/hashicorp/go-oracle-terraform/compute"
     9  	"github.com/hashicorp/packer/common/uuid"
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  type stepAddKeysToAPI struct{}
    15  
    16  func (s *stepAddKeysToAPI) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    17  	// get variables from state
    18  	ui := state.Get("ui").(packer.Ui)
    19  	config := state.Get("config").(*Config)
    20  	client := state.Get("client").(*compute.ComputeClient)
    21  
    22  	if config.Comm.Type != "ssh" {
    23  		ui.Say("Not using SSH communicator; skip generating SSH keys...")
    24  		return multistep.ActionContinue
    25  	}
    26  
    27  	// grab packer-generated key from statebag context.
    28  	sshPublicKey := bytes.TrimSpace(config.Comm.SSHPublicKey)
    29  
    30  	// form API call to add key to compute cloud
    31  	sshKeyName := fmt.Sprintf("/Compute-%s/%s/packer_generated_key_%s",
    32  		config.IdentityDomain, config.Username, uuid.TimeOrderedUUID())
    33  
    34  	ui.Say(fmt.Sprintf("Creating temporary key: %s", sshKeyName))
    35  
    36  	sshKeysClient := client.SSHKeys()
    37  	sshKeysInput := compute.CreateSSHKeyInput{
    38  		Name:    sshKeyName,
    39  		Key:     string(sshPublicKey),
    40  		Enabled: true,
    41  	}
    42  
    43  	// Load the packer-generated SSH key into the Oracle Compute cloud.
    44  	keyInfo, err := sshKeysClient.CreateSSHKey(&sshKeysInput)
    45  	if err != nil {
    46  		err = fmt.Errorf("Problem adding Public SSH key through Oracle's API: %s", err)
    47  		ui.Error(err.Error())
    48  		state.Put("error", err)
    49  		return multistep.ActionHalt
    50  	}
    51  	config.Comm.SSHKeyPairName = keyInfo.Name
    52  	return multistep.ActionContinue
    53  }
    54  
    55  func (s *stepAddKeysToAPI) Cleanup(state multistep.StateBag) {
    56  	// Delete the keys we created during this run
    57  	config := state.Get("config").(*Config)
    58  	if len(config.Comm.SSHKeyPairName) == 0 {
    59  		// No keys were generated; none need to be cleaned up.
    60  		return
    61  	}
    62  	ui := state.Get("ui").(packer.Ui)
    63  	ui.Say("Deleting SSH keys...")
    64  	deleteInput := compute.DeleteSSHKeyInput{Name: config.Comm.SSHKeyPairName}
    65  	client := state.Get("client").(*compute.ComputeClient)
    66  	deleteClient := client.SSHKeys()
    67  	err := deleteClient.DeleteSSHKey(&deleteInput)
    68  	if err != nil {
    69  		ui.Error(fmt.Sprintf("Error deleting SSH keys: %s", err.Error()))
    70  	}
    71  	return
    72  }