github.com/kimor79/packer@v0.8.7-0.20151221212622-d507b18eb4cf/helper/communicator/step_connect.go (about)

     1  package communicator
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/mitchellh/multistep"
     8  	gossh "golang.org/x/crypto/ssh"
     9  )
    10  
    11  // StepConnect is a multistep Step implementation that connects to
    12  // the proper communicator and stores it in the "communicator" key in the
    13  // state bag.
    14  type StepConnect struct {
    15  	// Config is the communicator config struct
    16  	Config *Config
    17  
    18  	// Host should return a host that can be connected to for communicator
    19  	// connections.
    20  	Host func(multistep.StateBag) (string, error)
    21  
    22  	// The fields below are callbacks to assist with connecting to SSH.
    23  	//
    24  	// SSHConfig should return the default configuration for
    25  	// connecting via SSH.
    26  	SSHConfig func(multistep.StateBag) (*gossh.ClientConfig, error)
    27  	SSHPort   func(multistep.StateBag) (int, error)
    28  
    29  	// The fields below are callbacks to assist with connecting to WinRM.
    30  	//
    31  	// WinRMConfig should return the default configuration for
    32  	// connecting via WinRM.
    33  	WinRMConfig func(multistep.StateBag) (*WinRMConfig, error)
    34  
    35  	// CustomConnect can be set to have custom connectors for specific
    36  	// types. These take highest precedence so you can also override
    37  	// existing types.
    38  	CustomConnect map[string]multistep.Step
    39  
    40  	substep multistep.Step
    41  }
    42  
    43  func (s *StepConnect) Run(state multistep.StateBag) multistep.StepAction {
    44  	typeMap := map[string]multistep.Step{
    45  		"none": nil,
    46  		"ssh": &StepConnectSSH{
    47  			Config:    s.Config,
    48  			Host:      s.Host,
    49  			SSHConfig: s.SSHConfig,
    50  			SSHPort:   s.SSHPort,
    51  		},
    52  		"winrm": &StepConnectWinRM{
    53  			Config:      s.Config,
    54  			Host:        s.Host,
    55  			WinRMConfig: s.WinRMConfig,
    56  			WinRMPort:   s.SSHPort,
    57  		},
    58  	}
    59  	for k, v := range s.CustomConnect {
    60  		typeMap[k] = v
    61  	}
    62  
    63  	step, ok := typeMap[s.Config.Type]
    64  	if !ok {
    65  		state.Put("error", fmt.Errorf("unknown communicator type: %s", s.Config.Type))
    66  		return multistep.ActionHalt
    67  	}
    68  
    69  	if step == nil {
    70  		log.Printf("[INFO] communicator disabled, will not connect")
    71  		return multistep.ActionContinue
    72  	}
    73  
    74  	s.substep = step
    75  	return s.substep.Run(state)
    76  }
    77  
    78  func (s *StepConnect) Cleanup(state multistep.StateBag) {
    79  	if s.substep != nil {
    80  		s.substep.Cleanup(state)
    81  	}
    82  }