github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/cloudstack/ssh.go (about)

     1  package cloudstack
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"os"
     7  
     8  	packerssh "github.com/hashicorp/packer/communicator/ssh"
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"golang.org/x/crypto/ssh"
    11  	"golang.org/x/crypto/ssh/agent"
    12  )
    13  
    14  func commHost(state multistep.StateBag) (string, error) {
    15  	ip, hasIP := state.Get("ipaddress").(string)
    16  	if !hasIP {
    17  		return "", fmt.Errorf("Failed to retrieve IP address")
    18  	}
    19  
    20  	return ip, nil
    21  }
    22  
    23  func commPort(state multistep.StateBag) (int, error) {
    24  	commPort, hasPort := state.Get("commPort").(int)
    25  	if !hasPort {
    26  		return 0, fmt.Errorf("Failed to retrieve communication port")
    27  	}
    28  
    29  	return commPort, nil
    30  }
    31  
    32  func sshConfig(useAgent bool, username, password string) func(state multistep.StateBag) (*ssh.ClientConfig, error) {
    33  	return func(state multistep.StateBag) (*ssh.ClientConfig, error) {
    34  		if useAgent {
    35  			authSock := os.Getenv("SSH_AUTH_SOCK")
    36  			if authSock == "" {
    37  				return nil, fmt.Errorf("SSH_AUTH_SOCK is not set")
    38  			}
    39  
    40  			sshAgent, err := net.Dial("unix", authSock)
    41  			if err != nil {
    42  				return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err)
    43  			}
    44  
    45  			return &ssh.ClientConfig{
    46  				User: username,
    47  				Auth: []ssh.AuthMethod{
    48  					ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
    49  				},
    50  				HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    51  			}, nil
    52  		}
    53  
    54  		privateKey, hasKey := state.GetOk("privateKey")
    55  
    56  		if hasKey {
    57  			signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string)))
    58  			if err != nil {
    59  				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    60  			}
    61  
    62  			return &ssh.ClientConfig{
    63  				User: username,
    64  				Auth: []ssh.AuthMethod{
    65  					ssh.PublicKeys(signer),
    66  				},
    67  				HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    68  			}, nil
    69  
    70  		} else {
    71  
    72  			return &ssh.ClientConfig{
    73  				User:            username,
    74  				HostKeyCallback: ssh.InsecureIgnoreHostKey(),
    75  				Auth: []ssh.AuthMethod{
    76  					ssh.Password(password),
    77  					ssh.KeyboardInteractive(
    78  						packerssh.PasswordKeyboardInteractive(password)),
    79  				}}, nil
    80  		}
    81  	}
    82  }