github.com/angdraug/packer@v1.3.2/builder/digitalocean/step_create_ssh_key.go (about)

     1  package digitalocean
     2  
     3  import (
     4  	"context"
     5  	"crypto/rand"
     6  	"crypto/rsa"
     7  	"crypto/x509"
     8  	"encoding/pem"
     9  	"fmt"
    10  	"log"
    11  	"os"
    12  	"runtime"
    13  
    14  	"github.com/digitalocean/godo"
    15  	"github.com/hashicorp/packer/common/uuid"
    16  	"github.com/hashicorp/packer/helper/multistep"
    17  	"github.com/hashicorp/packer/packer"
    18  	"golang.org/x/crypto/ssh"
    19  )
    20  
    21  type stepCreateSSHKey struct {
    22  	Debug        bool
    23  	DebugKeyPath string
    24  
    25  	keyId int
    26  }
    27  
    28  func (s *stepCreateSSHKey) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    29  	client := state.Get("client").(*godo.Client)
    30  	ui := state.Get("ui").(packer.Ui)
    31  	c := state.Get("config").(*Config)
    32  
    33  	ui.Say("Creating temporary ssh key for droplet...")
    34  
    35  	priv, err := rsa.GenerateKey(rand.Reader, 2014)
    36  
    37  	// ASN.1 DER encoded form
    38  	priv_der := x509.MarshalPKCS1PrivateKey(priv)
    39  	priv_blk := pem.Block{
    40  		Type:    "RSA PRIVATE KEY",
    41  		Headers: nil,
    42  		Bytes:   priv_der,
    43  	}
    44  
    45  	// Set the private key in the config for later
    46  	c.Comm.SSHPrivateKey = pem.EncodeToMemory(&priv_blk)
    47  
    48  	// Marshal the public key into SSH compatible format
    49  	// TODO properly handle the public key error
    50  	pub, _ := ssh.NewPublicKey(&priv.PublicKey)
    51  	pub_sshformat := string(ssh.MarshalAuthorizedKey(pub))
    52  
    53  	// The name of the public key on DO
    54  	name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
    55  
    56  	// Create the key!
    57  	key, _, err := client.Keys.Create(context.TODO(), &godo.KeyCreateRequest{
    58  		Name:      name,
    59  		PublicKey: pub_sshformat,
    60  	})
    61  	if err != nil {
    62  		err := fmt.Errorf("Error creating temporary SSH key: %s", err)
    63  		state.Put("error", err)
    64  		ui.Error(err.Error())
    65  		return multistep.ActionHalt
    66  	}
    67  
    68  	// We use this to check cleanup
    69  	s.keyId = key.ID
    70  
    71  	log.Printf("temporary ssh key name: %s", name)
    72  
    73  	// Remember some state for the future
    74  	state.Put("ssh_key_id", key.ID)
    75  
    76  	// If we're in debug mode, output the private key to the working directory.
    77  	if s.Debug {
    78  		ui.Message(fmt.Sprintf("Saving key for debug purposes: %s", s.DebugKeyPath))
    79  		f, err := os.Create(s.DebugKeyPath)
    80  		if err != nil {
    81  			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
    82  			return multistep.ActionHalt
    83  		}
    84  		defer f.Close()
    85  
    86  		// Write the key out
    87  		if _, err := f.Write(pem.EncodeToMemory(&priv_blk)); err != nil {
    88  			state.Put("error", fmt.Errorf("Error saving debug key: %s", err))
    89  			return multistep.ActionHalt
    90  		}
    91  
    92  		// Chmod it so that it is SSH ready
    93  		if runtime.GOOS != "windows" {
    94  			if err := f.Chmod(0600); err != nil {
    95  				state.Put("error", fmt.Errorf("Error setting permissions of debug key: %s", err))
    96  				return multistep.ActionHalt
    97  			}
    98  		}
    99  	}
   100  
   101  	return multistep.ActionContinue
   102  }
   103  
   104  func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) {
   105  	// If no key name is set, then we never created it, so just return
   106  	if s.keyId == 0 {
   107  		return
   108  	}
   109  
   110  	client := state.Get("client").(*godo.Client)
   111  	ui := state.Get("ui").(packer.Ui)
   112  
   113  	ui.Say("Deleting temporary ssh key...")
   114  	_, err := client.Keys.DeleteByID(context.TODO(), s.keyId)
   115  	if err != nil {
   116  		log.Printf("Error cleaning up ssh key: %s", err)
   117  		ui.Error(fmt.Sprintf(
   118  			"Error cleaning up ssh key. Please delete the key manually: %s", err))
   119  	}
   120  }