github.com/rothwerx/packer@v0.9.0/builder/vmware/common/ssh.go (about)

     1  package common
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"log"
     8  	"os"
     9  
    10  	"github.com/mitchellh/multistep"
    11  	commonssh "github.com/mitchellh/packer/common/ssh"
    12  	"github.com/mitchellh/packer/communicator/ssh"
    13  	gossh "golang.org/x/crypto/ssh"
    14  )
    15  
    16  func CommHost(config *SSHConfig) func(multistep.StateBag) (string, error) {
    17  	return func(state multistep.StateBag) (string, error) {
    18  		driver := state.Get("driver").(Driver)
    19  		vmxPath := state.Get("vmx_path").(string)
    20  
    21  		if config.Comm.SSHHost != "" {
    22  			return config.Comm.SSHHost, nil
    23  		}
    24  
    25  		log.Println("Lookup up IP information...")
    26  		f, err := os.Open(vmxPath)
    27  		if err != nil {
    28  			return "", err
    29  		}
    30  		defer f.Close()
    31  
    32  		vmxBytes, err := ioutil.ReadAll(f)
    33  		if err != nil {
    34  			return "", err
    35  		}
    36  
    37  		vmxData := ParseVMX(string(vmxBytes))
    38  
    39  		var ok bool
    40  		macAddress := ""
    41  		if macAddress, ok = vmxData["ethernet0.address"]; !ok || macAddress == "" {
    42  			if macAddress, ok = vmxData["ethernet0.generatedaddress"]; !ok || macAddress == "" {
    43  				return "", errors.New("couldn't find MAC address in VMX")
    44  			}
    45  		}
    46  
    47  		ipLookup := &DHCPLeaseGuestLookup{
    48  			Driver:     driver,
    49  			Device:     "vmnet8",
    50  			MACAddress: macAddress,
    51  		}
    52  
    53  		ipAddress, err := ipLookup.GuestIP()
    54  		if err != nil {
    55  			log.Printf("IP lookup failed: %s", err)
    56  			return "", fmt.Errorf("IP lookup failed: %s", err)
    57  		}
    58  
    59  		if ipAddress == "" {
    60  			log.Println("IP is blank, no IP yet.")
    61  			return "", errors.New("IP is blank")
    62  		}
    63  
    64  		log.Printf("Detected IP: %s", ipAddress)
    65  		return ipAddress, nil
    66  	}
    67  }
    68  
    69  func SSHConfigFunc(config *SSHConfig) func(multistep.StateBag) (*gossh.ClientConfig, error) {
    70  	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
    71  		auth := []gossh.AuthMethod{
    72  			gossh.Password(config.Comm.SSHPassword),
    73  			gossh.KeyboardInteractive(
    74  				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
    75  		}
    76  
    77  		if config.Comm.SSHPrivateKey != "" {
    78  			signer, err := commonssh.FileSigner(config.Comm.SSHPrivateKey)
    79  			if err != nil {
    80  				return nil, err
    81  			}
    82  
    83  			auth = append(auth, gossh.PublicKeys(signer))
    84  		}
    85  
    86  		return &gossh.ClientConfig{
    87  			User: config.Comm.SSHUsername,
    88  			Auth: auth,
    89  		}, nil
    90  	}
    91  }