github.com/sneal/packer@v0.5.2/builder/qemu/step_forward_ssh.go (about) 1 package qemu 2 3 import ( 4 "fmt" 5 "github.com/mitchellh/multistep" 6 "github.com/mitchellh/packer/packer" 7 "log" 8 "math/rand" 9 "net" 10 ) 11 12 // This step adds a NAT port forwarding definition so that SSH is available 13 // on the guest machine. 14 // 15 // Uses: 16 // 17 // Produces: 18 type stepForwardSSH struct{} 19 20 func (s *stepForwardSSH) Run(state multistep.StateBag) multistep.StepAction { 21 config := state.Get("config").(*config) 22 ui := state.Get("ui").(packer.Ui) 23 24 log.Printf("Looking for available SSH port between %d and %d", config.SSHHostPortMin, config.SSHHostPortMax) 25 var sshHostPort uint 26 portRange := int(config.SSHHostPortMax - config.SSHHostPortMin) 27 for { 28 sshHostPort = uint(rand.Intn(portRange)) + config.SSHHostPortMin 29 log.Printf("Trying port: %d", sshHostPort) 30 l, err := net.Listen("tcp", fmt.Sprintf(":%d", sshHostPort)) 31 if err == nil { 32 defer l.Close() 33 break 34 } 35 } 36 ui.Say(fmt.Sprintf("Found port for SSH: %d.", sshHostPort)) 37 38 // Save the port we're using so that future steps can use it 39 state.Put("sshHostPort", sshHostPort) 40 41 return multistep.ActionContinue 42 } 43 44 func (s *stepForwardSSH) Cleanup(state multistep.StateBag) {}