github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/virtualbox/common/step_forward_ssh.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"math/rand"
     7  	"net"
     8  
     9  	"github.com/hashicorp/packer/helper/communicator"
    10  	"github.com/hashicorp/packer/packer"
    11  	"github.com/mitchellh/multistep"
    12  )
    13  
    14  // This step adds a NAT port forwarding definition so that SSH is available
    15  // on the guest machine.
    16  //
    17  // Uses:
    18  //   driver Driver
    19  //   ui packer.Ui
    20  //   vmName string
    21  //
    22  // Produces:
    23  type StepForwardSSH struct {
    24  	CommConfig     *communicator.Config
    25  	HostPortMin    uint
    26  	HostPortMax    uint
    27  	SkipNatMapping bool
    28  }
    29  
    30  func (s *StepForwardSSH) Run(state multistep.StateBag) multistep.StepAction {
    31  	driver := state.Get("driver").(Driver)
    32  	ui := state.Get("ui").(packer.Ui)
    33  	vmName := state.Get("vmName").(string)
    34  
    35  	if s.CommConfig.Type == "none" {
    36  		log.Printf("Not using a communicator, skipping setting up port forwarding...")
    37  		state.Put("sshHostPort", 0)
    38  		return multistep.ActionContinue
    39  	}
    40  
    41  	guestPort := s.CommConfig.Port()
    42  	sshHostPort := guestPort
    43  	if !s.SkipNatMapping {
    44  		log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d",
    45  			s.HostPortMin, s.HostPortMax)
    46  
    47  		portRange := int(s.HostPortMax - s.HostPortMin + 1)
    48  		offset := rand.Intn(portRange)
    49  
    50  		for {
    51  			sshHostPort = offset + int(s.HostPortMin)
    52  			log.Printf("Trying port: %d", sshHostPort)
    53  			l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort))
    54  			if err == nil {
    55  				defer l.Close()
    56  				break
    57  			}
    58  			offset++
    59  			if offset == portRange {
    60  				offset = 0
    61  			}
    62  		}
    63  
    64  		// Create a forwarded port mapping to the VM
    65  		ui.Say(fmt.Sprintf("Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port %d)", sshHostPort))
    66  		command := []string{
    67  			"modifyvm", vmName,
    68  			"--natpf1",
    69  			fmt.Sprintf("packercomm,tcp,127.0.0.1,%d,,%d", sshHostPort, guestPort),
    70  		}
    71  		if err := driver.VBoxManage(command...); err != nil {
    72  			err := fmt.Errorf("Error creating port forwarding rule: %s", err)
    73  			state.Put("error", err)
    74  			ui.Error(err.Error())
    75  			return multistep.ActionHalt
    76  		}
    77  	}
    78  
    79  	// Save the port we're using so that future steps can use it
    80  	state.Put("sshHostPort", sshHostPort)
    81  
    82  	return multistep.ActionContinue
    83  }
    84  
    85  func (s *StepForwardSSH) Cleanup(state multistep.StateBag) {}