github.com/sneal/packer@v0.5.2/builder/virtualbox/common/ssh_config.go (about)

     1  package common
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"github.com/mitchellh/packer/packer"
     7  	"os"
     8  	"time"
     9  )
    10  
    11  type SSHConfig struct {
    12  	SSHHostPortMin    uint   `mapstructure:"ssh_host_port_min"`
    13  	SSHHostPortMax    uint   `mapstructure:"ssh_host_port_max"`
    14  	SSHKeyPath        string `mapstructure:"ssh_key_path"`
    15  	SSHPassword       string `mapstructure:"ssh_password"`
    16  	SSHPort           uint   `mapstructure:"ssh_port"`
    17  	SSHUser           string `mapstructure:"ssh_username"`
    18  	RawSSHWaitTimeout string `mapstructure:"ssh_wait_timeout"`
    19  
    20  	SSHWaitTimeout time.Duration
    21  }
    22  
    23  func (c *SSHConfig) Prepare(t *packer.ConfigTemplate) []error {
    24  	if c.SSHHostPortMin == 0 {
    25  		c.SSHHostPortMin = 2222
    26  	}
    27  
    28  	if c.SSHHostPortMax == 0 {
    29  		c.SSHHostPortMax = 4444
    30  	}
    31  
    32  	if c.SSHPort == 0 {
    33  		c.SSHPort = 22
    34  	}
    35  
    36  	if c.RawSSHWaitTimeout == "" {
    37  		c.RawSSHWaitTimeout = "20m"
    38  	}
    39  
    40  	templates := map[string]*string{
    41  		"ssh_key_path":     &c.SSHKeyPath,
    42  		"ssh_password":     &c.SSHPassword,
    43  		"ssh_username":     &c.SSHUser,
    44  		"ssh_wait_timeout": &c.RawSSHWaitTimeout,
    45  	}
    46  
    47  	errs := make([]error, 0)
    48  	for n, ptr := range templates {
    49  		var err error
    50  		*ptr, err = t.Process(*ptr, nil)
    51  		if err != nil {
    52  			errs = append(errs, fmt.Errorf("Error processing %s: %s", n, err))
    53  		}
    54  	}
    55  
    56  	if c.SSHKeyPath != "" {
    57  		if _, err := os.Stat(c.SSHKeyPath); err != nil {
    58  			errs = append(errs, fmt.Errorf("ssh_key_path is invalid: %s", err))
    59  		} else if _, err := sshKeyToKeyring(c.SSHKeyPath); err != nil {
    60  			errs = append(errs, fmt.Errorf("ssh_key_path is invalid: %s", err))
    61  		}
    62  	}
    63  
    64  	if c.SSHHostPortMin > c.SSHHostPortMax {
    65  		errs = append(errs,
    66  			errors.New("ssh_host_port_min must be less than ssh_host_port_max"))
    67  	}
    68  
    69  	if c.SSHUser == "" {
    70  		errs = append(errs, errors.New("An ssh_username must be specified."))
    71  	}
    72  
    73  	var err error
    74  	c.SSHWaitTimeout, err = time.ParseDuration(c.RawSSHWaitTimeout)
    75  	if err != nil {
    76  		errs = append(errs, fmt.Errorf("Failed parsing ssh_wait_timeout: %s", err))
    77  	}
    78  
    79  	return errs
    80  }