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