github.com/rothwerx/packer@v0.9.0/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/mitchellh/multistep" 10 "github.com/mitchellh/packer/helper/communicator" 11 "github.com/mitchellh/packer/packer" 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 guestPort := s.CommConfig.Port() 36 sshHostPort := guestPort 37 if !s.SkipNatMapping { 38 log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d", 39 s.HostPortMin, s.HostPortMax) 40 offset := 0 41 42 portRange := int(s.HostPortMax - s.HostPortMin) 43 if portRange > 0 { 44 // Have to check if > 0 to avoid a panic 45 offset = rand.Intn(portRange) 46 } 47 48 for { 49 sshHostPort = offset + int(s.HostPortMin) 50 if sshHostPort >= int(s.HostPortMax) { 51 offset = 0 52 sshHostPort = int(s.HostPortMin) 53 } 54 log.Printf("Trying port: %d", sshHostPort) 55 l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort)) 56 if err == nil { 57 defer l.Close() 58 break 59 } 60 offset++ 61 } 62 63 // Create a forwarded port mapping to the VM 64 ui.Say(fmt.Sprintf("Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port %d)", sshHostPort)) 65 command := []string{ 66 "modifyvm", vmName, 67 "--natpf1", 68 fmt.Sprintf("packercomm,tcp,127.0.0.1,%d,,%d", sshHostPort, guestPort), 69 } 70 if err := driver.VBoxManage(command...); err != nil { 71 err := fmt.Errorf("Error creating port forwarding rule: %s", err) 72 state.Put("error", err) 73 ui.Error(err.Error()) 74 return multistep.ActionHalt 75 } 76 } 77 78 // Save the port we're using so that future steps can use it 79 state.Put("sshHostPort", sshHostPort) 80 81 return multistep.ActionContinue 82 } 83 84 func (s *StepForwardSSH) Cleanup(state multistep.StateBag) {}