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