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

     1  package null
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/communicator/ssh"
     7  	gossh "golang.org/x/crypto/ssh"
     8  	"io/ioutil"
     9  )
    10  
    11  func CommHost(host string) func(multistep.StateBag) (string, error) {
    12  	return func(state multistep.StateBag) (string, error) {
    13  		return host, nil
    14  	}
    15  }
    16  
    17  // SSHConfig returns a function that can be used for the SSH communicator
    18  // config for connecting to the specified host via SSH
    19  // private_key_file has precedence over password!
    20  func SSHConfig(username string, password string, privateKeyFile string) func(multistep.StateBag) (*gossh.ClientConfig, error) {
    21  	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
    22  
    23  		if privateKeyFile != "" {
    24  			// key based auth
    25  
    26  			bytes, err := ioutil.ReadFile(privateKeyFile)
    27  			if err != nil {
    28  				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    29  			}
    30  			privateKey := string(bytes)
    31  
    32  			signer, err := gossh.ParsePrivateKey([]byte(privateKey))
    33  			if err != nil {
    34  				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
    35  			}
    36  
    37  			return &gossh.ClientConfig{
    38  				User: username,
    39  				Auth: []gossh.AuthMethod{
    40  					gossh.PublicKeys(signer),
    41  				},
    42  			}, nil
    43  		} else {
    44  			// password based auth
    45  
    46  			return &gossh.ClientConfig{
    47  				User: username,
    48  				Auth: []gossh.AuthMethod{
    49  					gossh.Password(password),
    50  					gossh.KeyboardInteractive(
    51  						ssh.PasswordKeyboardInteractive(password)),
    52  				},
    53  			}, nil
    54  		}
    55  	}
    56  }