File: post-processor.go

package info (click to toggle)
packer 1.6.6%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 32,016 kB
  • sloc: sh: 1,154; python: 619; makefile: 251; ruby: 205; xml: 97
file content (279 lines) | stat: -rw-r--r-- 7,892 bytes parent folder | download | duplicates (2)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//go:generate mapstructure-to-hcl2 -type Config

package vsphere

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"net/url"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
	"time"

	"github.com/hashicorp/hcl/v2/hcldec"
	"github.com/hashicorp/packer/packer-plugin-sdk/common"
	packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
	shelllocal "github.com/hashicorp/packer/packer-plugin-sdk/shell-local"
	"github.com/hashicorp/packer/packer-plugin-sdk/template/config"
	"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
)

var ovftool string = "ovftool"

var (
	// Regular expression to validate RFC1035 hostnames from full fqdn or simple hostname.
	// For example "packer-esxi1". Requires proper DNS setup and/or correct DNS search domain setting.
	hostnameRegex = regexp.MustCompile(`^[[:alnum:]][[:alnum:]\-]{0,61}[[:alnum:]]|[[:alpha:]]$`)

	// Simple regular expression to validate IPv4 values.
	// For example "192.168.1.1".
	ipv4Regex = regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)
)

type Config struct {
	common.PackerConfig `mapstructure:",squash"`

	Cluster      string   `mapstructure:"cluster"`
	Datacenter   string   `mapstructure:"datacenter"`
	Datastore    string   `mapstructure:"datastore"`
	DiskMode     string   `mapstructure:"disk_mode"`
	Host         string   `mapstructure:"host"`
	ESXiHost     string   `mapstructure:"esxi_host"`
	Insecure     bool     `mapstructure:"insecure"`
	Options      []string `mapstructure:"options"`
	Overwrite    bool     `mapstructure:"overwrite"`
	Password     string   `mapstructure:"password"`
	ResourcePool string   `mapstructure:"resource_pool"`
	Username     string   `mapstructure:"username"`
	VMFolder     string   `mapstructure:"vm_folder"`
	VMName       string   `mapstructure:"vm_name"`
	VMNetwork    string   `mapstructure:"vm_network"`

	ctx interpolate.Context
}

type PostProcessor struct {
	config Config
}

func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }

func (p *PostProcessor) Configure(raws ...interface{}) error {
	err := config.Decode(&p.config, &config.DecodeOpts{
		PluginType:         BuilderId,
		Interpolate:        true,
		InterpolateContext: &p.config.ctx,
		InterpolateFilter: &interpolate.RenderFilter{
			Exclude: []string{},
		},
	}, raws...)
	if err != nil {
		return err
	}

	// Defaults
	if p.config.DiskMode == "" {
		p.config.DiskMode = "thick"
	}

	// Accumulate any errors
	errs := new(packersdk.MultiError)

	if runtime.GOOS == "windows" {
		ovftool = "ovftool.exe"
	}

	if _, err := exec.LookPath(ovftool); err != nil {
		errs = packersdk.MultiErrorAppend(
			errs, fmt.Errorf("ovftool not found: %s", err))
	}

	// First define all our templatable parameters that are _required_
	templates := map[string]*string{
		"cluster":    &p.config.Cluster,
		"datacenter": &p.config.Datacenter,
		"diskmode":   &p.config.DiskMode,
		"host":       &p.config.Host,
		"password":   &p.config.Password,
		"username":   &p.config.Username,
		"vm_name":    &p.config.VMName,
	}
	for key, ptr := range templates {
		if *ptr == "" {
			errs = packersdk.MultiErrorAppend(
				errs, fmt.Errorf("%s must be set", key))
		}
	}

	if len(errs.Errors) > 0 {
		return errs
	}

	return nil
}

func (p *PostProcessor) generateURI() (*url.URL, error) {
	// use net/url lib to encode and escape url elements
	ovftool_uri := fmt.Sprintf("vi://%s/%s/host/%s",
		p.config.Host,
		p.config.Datacenter,
		p.config.Cluster)

	if p.config.ResourcePool != "" {
		ovftool_uri += "/Resources/" + p.config.ResourcePool
	}

	u, err := url.Parse(ovftool_uri)
	if err != nil {
		return nil, fmt.Errorf("Couldn't generate uri for ovftool: %s", err)
	}
	u.User = url.UserPassword(p.config.Username, p.config.Password)

	if p.config.ESXiHost != "" {
		q := u.Query()
		if ipv4Regex.MatchString(p.config.ESXiHost) {
			q.Add("ip", p.config.ESXiHost)
		} else if hostnameRegex.MatchString(p.config.ESXiHost) {
			q.Add("dns", p.config.ESXiHost)
		}
		u.RawQuery = q.Encode()
	}
	return u, nil
}

func getEncodedPassword(u *url.URL) (string, bool) {
	// filter password from all logging
	password, passwordSet := u.User.Password()
	if passwordSet && password != "" {
		encodedPassword := strings.Split(u.User.String(), ":")[1]
		return encodedPassword, true
	}
	return password, false
}

func (p *PostProcessor) PostProcess(ctx context.Context, ui packersdk.Ui, artifact packersdk.Artifact) (packersdk.Artifact, bool, bool, error) {
	source := ""
	for _, path := range artifact.Files() {
		if strings.HasSuffix(path, ".vmx") || strings.HasSuffix(path, ".ovf") || strings.HasSuffix(path, ".ova") {
			source = path
			break
		}
	}

	if source == "" {
		return nil, false, false, fmt.Errorf("VMX, OVF or OVA file not found")
	}

	ovftool_uri, err := p.generateURI()
	if err != nil {
		return nil, false, false, err
	}
	encodedPassword, isSet := getEncodedPassword(ovftool_uri)
	if isSet {
		packersdk.LogSecretFilter.Set(encodedPassword)
	}

	args, err := p.BuildArgs(source, ovftool_uri.String())
	if err != nil {
		ui.Message(fmt.Sprintf("Failed: %s\n", err))
	}

	ui.Message(fmt.Sprintf("Uploading %s to vSphere", source))

	log.Printf("Starting ovftool with parameters: %s", strings.Join(args, " "))

	ui.Message("Validating Username and Password with dry-run")
	err = p.ValidateOvfTool(args, ovftool)
	if err != nil {
		return nil, false, false, err
	}

	// Validation has passed, so run for real.
	ui.Message("Calling OVFtool to upload vm")
	commandAndArgs := []string{ovftool}
	commandAndArgs = append(commandAndArgs, args...)
	comm := &shelllocal.Communicator{
		ExecuteCommand: commandAndArgs,
	}
	flattenedCmd := strings.Join(commandAndArgs, " ")
	cmd := &packersdk.RemoteCmd{Command: flattenedCmd}
	log.Printf("[INFO] (vsphere): starting ovftool command: %s", flattenedCmd)
	if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
		return nil, false, false, fmt.Errorf(
			"Error uploading virtual machine: Please see output above for more information.")
	}

	artifact = NewArtifact(p.config.Datastore, p.config.VMFolder, p.config.VMName, artifact.Files())

	return artifact, false, false, nil
}

func (p *PostProcessor) ValidateOvfTool(args []string, ofvtool string) error {
	args = append([]string{"--verifyOnly"}, args...)
	var out bytes.Buffer
	cmdCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	cmd := exec.CommandContext(cmdCtx, ovftool, args...)
	cmd.Stdout = &out

	// Need to manually close stdin or else the ofvtool call will hang
	// forever in a situation where the user has provided an invalid
	// password or username
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}
	defer stdin.Close()

	if err := cmd.Run(); err != nil {
		outString := out.String()
		if strings.Contains(outString, "Enter login information for") {
			err = fmt.Errorf("Error performing OVFtool dry run; the username " +
				"or password you provided to ovftool is likely invalid.")
			return err
		}
		return nil
	}
	return nil
}

func (p *PostProcessor) BuildArgs(source, ovftool_uri string) ([]string, error) {
	args := []string{
		"--acceptAllEulas",
		fmt.Sprintf(`--name=%s`, p.config.VMName),
		fmt.Sprintf(`--datastore=%s`, p.config.Datastore),
	}

	if p.config.Insecure {
		args = append(args, fmt.Sprintf(`--noSSLVerify=%t`, p.config.Insecure))
	}

	if p.config.DiskMode != "" {
		args = append(args, fmt.Sprintf(`--diskMode=%s`, p.config.DiskMode))
	}

	if p.config.VMFolder != "" {
		args = append(args, fmt.Sprintf(`--vmFolder=%s`, p.config.VMFolder))
	}

	if p.config.VMNetwork != "" {
		args = append(args, fmt.Sprintf(`--network=%s`, p.config.VMNetwork))
	}

	if p.config.Overwrite == true {
		args = append(args, "--overwrite")
	}

	if len(p.config.Options) > 0 {
		args = append(args, p.config.Options...)
	}

	args = append(args, source)
	args = append(args, ovftool_uri)

	return args, nil
}