File: step_forward_ssh.go

package info (click to toggle)
packer 1.3.4%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 8,324 kB
  • sloc: python: 619; sh: 557; makefile: 111
file content (86 lines) | stat: -rw-r--r-- 2,236 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package common

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"net"

	"github.com/hashicorp/packer/helper/communicator"
	"github.com/hashicorp/packer/helper/multistep"
	"github.com/hashicorp/packer/packer"
)

// This step adds a NAT port forwarding definition so that SSH is available
// on the guest machine.
//
// Uses:
//   driver Driver
//   ui packer.Ui
//   vmName string
//
// Produces:
type StepForwardSSH struct {
	CommConfig     *communicator.Config
	HostPortMin    uint
	HostPortMax    uint
	SkipNatMapping bool
}

func (s *StepForwardSSH) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)
	vmName := state.Get("vmName").(string)

	if s.CommConfig.Type == "none" {
		log.Printf("Not using a communicator, skipping setting up port forwarding...")
		state.Put("sshHostPort", 0)
		return multistep.ActionContinue
	}

	guestPort := s.CommConfig.Port()
	sshHostPort := guestPort
	if !s.SkipNatMapping {
		log.Printf("Looking for available communicator (SSH, WinRM, etc) port between %d and %d",
			s.HostPortMin, s.HostPortMax)

		portRange := int(s.HostPortMax - s.HostPortMin + 1)
		offset := rand.Intn(portRange)

		for {
			sshHostPort = offset + int(s.HostPortMin)
			log.Printf("Trying port: %d", sshHostPort)
			l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", sshHostPort))
			if err == nil {
				defer l.Close()
				break
			}
			offset++
			if offset == portRange {
				offset = 0
			}
		}

		// Create a forwarded port mapping to the VM
		ui.Say(fmt.Sprintf("Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port %d)", sshHostPort))
		command := []string{
			"modifyvm", vmName,
			"--natpf1",
			fmt.Sprintf("packercomm,tcp,127.0.0.1,%d,,%d", sshHostPort, guestPort),
		}
		if err := driver.VBoxManage(command...); err != nil {
			err := fmt.Errorf("Error creating port forwarding rule: %s", err)
			state.Put("error", err)
			ui.Error(err.Error())
			return multistep.ActionHalt
		}
	}

	// Save the port we're using so that future steps can use it
	state.Put("sshHostPort", sshHostPort)

	return multistep.ActionContinue
}

func (s *StepForwardSSH) Cleanup(state multistep.StateBag) {}