github.com/rothwerx/packer@v0.9.0/builder/digitalocean/step_create_ssh_key.go (about)

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