github.phpd.cn/hashicorp/packer@v1.3.2/builder/hcloud/step_create_sshkey.go (about)

     1  package hcloud
     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/hashicorp/packer/common/uuid"
    15  	"github.com/hashicorp/packer/helper/multistep"
    16  	"github.com/hashicorp/packer/packer"
    17  	"github.com/hetznercloud/hcloud-go/hcloud"
    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("hcloudClient").(*hcloud.Client)
    30  	ui := state.Get("ui").(packer.Ui)
    31  	c := state.Get("config").(*Config)
    32  	ui.Say("Creating temporary ssh key for server...")
    33  
    34  	priv, err := rsa.GenerateKey(rand.Reader, 2014)
    35  
    36  	// ASN.1 DER encoded form
    37  	privDER := x509.MarshalPKCS1PrivateKey(priv)
    38  	privBLK := pem.Block{
    39  		Type:    "RSA PRIVATE KEY",
    40  		Headers: nil,
    41  		Bytes:   privDER,
    42  	}
    43  
    44  	// Set the private key in the config for later
    45  	c.Comm.SSHPrivateKey = pem.EncodeToMemory(&privBLK)
    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  	pubSSHFormat := string(ssh.MarshalAuthorizedKey(pub))
    51  
    52  	// The name of the public key on the Hetzner Cloud
    53  	name := fmt.Sprintf("packer-%s", uuid.TimeOrderedUUID())
    54  
    55  	// Create the key!
    56  	key, _, err := client.SSHKey.Create(context.TODO(), hcloud.SSHKeyCreateOpts{
    57  		Name:      name,
    58  		PublicKey: pubSSHFormat,
    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(&privBLK)); 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  	return multistep.ActionContinue
   100  }
   101  
   102  func (s *stepCreateSSHKey) Cleanup(state multistep.StateBag) {
   103  	// If no key id is set, then we never created it, so just return
   104  	if s.keyId == 0 {
   105  		return
   106  	}
   107  
   108  	client := state.Get("hcloudClient").(*hcloud.Client)
   109  	ui := state.Get("ui").(packer.Ui)
   110  
   111  	ui.Say("Deleting temporary ssh key...")
   112  	_, err := client.SSHKey.Delete(context.TODO(), &hcloud.SSHKey{ID: 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  }