forked from YaleUniversity/packer-plugin-goss
-
Notifications
You must be signed in to change notification settings - Fork 1
/
packer-provisioner-goss.go
520 lines (446 loc) · 14.1 KB
/
packer-provisioner-goss.go
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//go:generate mapstructure-to-hcl2 -type GossConfig
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/plugin"
"github.com/hashicorp/packer/template/interpolate"
)
const gossSpecFile = "/tmp/goss-spec.yaml"
const gossDebugSpecFile = "/tmp/debug-goss-spec.yaml"
// GossConfig holds the config data coming in from the packer template
type GossConfig struct {
// Goss installation
Version string
Arch string
URL string
DownloadPath string
Username string
Password string
SkipInstall bool
Inspect bool
// An array of tests to run.
Tests []string
// Goss options for retry and timeouts
RetryTimeout string `mapstructure:"retry_timeout"`
Sleep string `mapstructure:"sleep"`
// Use Sudo
UseSudo bool `mapstructure:"use_sudo"`
// skip ssl check flag
SkipSSLChk bool `mapstructure:"skip_ssl"`
// The --gossfile flag
GossFile string `mapstructure:"goss_file"`
// The --vars flag
// Optional file containing variables, used within GOSS templating.
// Must be one of the files contained in the Tests array.
// Can be YAML or JSON.
VarsFile string `mapstructure:"vars_file"`
// The --vars-inline flag
// Optional inline variables that overrides JSON file vars
VarsInline map[string]string `mapstructure:"vars_inline"`
// Optional env variables
VarsEnv map[string]string `mapstructure:"vars_env"`
// The remote folder where the goss tests will be uploaded to.
// This should be set to a pre-existing directory, it defaults to /tmp
RemoteFolder string `mapstructure:"remote_folder"`
// The remote path where the goss tests will be uploaded.
// This defaults to remote_folder/goss
RemotePath string `mapstructure:"remote_path"`
// The format to use for test output
// Available: [documentation json json_oneline junit nagios nagios_verbose rspecish silent tap]
// Default: rspecish
Format string `mapstructure:"format"`
// The format options to use for printing test output
// Available: [perfdata verbose pretty]
// Default: verbose
FormatOptions string `mapstructure:"format_options"`
ctx interpolate.Context
}
var validFormats = []string{"documentation", "json", "json_oneline", "junit", "nagios", "nagios_verbose", "rspecish", "silent", "tap"}
var validFormatOptions = []string{"perfdata", "verbose", "pretty"}
// Provisioner implements a packer Provisioner
type Provisioner struct {
config GossConfig
}
func main() {
server, err := plugin.Server()
if err != nil {
panic(err)
}
server.RegisterProvisioner(new(Provisioner))
server.Serve()
}
func (p *Provisioner) ConfigSpec() hcldec.ObjectSpec {
return p.config.FlatMapstructure().HCL2Spec()
}
// Prepare gets the Goss Privisioner ready to run
func (p *Provisioner) Prepare(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
if err != nil {
return err
}
if p.config.Version == "" {
p.config.Version = "0.3.9"
}
if p.config.Arch == "" {
p.config.Arch = "amd64"
}
if p.config.URL == "" {
p.config.URL = fmt.Sprintf(
"https://github.com/aelsabbahy/goss/releases/download/v%s/goss-linux-%s",
p.config.Version, p.config.Arch)
}
if p.config.DownloadPath == "" {
if p.config.URL == "" {
p.config.DownloadPath = fmt.Sprintf("/tmp/goss-%s-linux-%s", p.config.Version, p.config.Arch)
} else {
list := strings.Split(p.config.URL, "/")
arch := strings.Split(list[len(list)-1], "-")[2]
version := strings.TrimPrefix(list[len(list)-2], "v")
p.config.DownloadPath = fmt.Sprintf("/tmp/goss-%s-linux-%s", version, arch)
}
}
if p.config.RemoteFolder == "" {
p.config.RemoteFolder = "/tmp"
}
if p.config.RemotePath == "" {
p.config.RemotePath = fmt.Sprintf("%s/goss", p.config.RemoteFolder)
}
if p.config.Tests == nil {
p.config.Tests = make([]string, 0)
}
if p.config.GossFile != "" {
p.config.GossFile = fmt.Sprintf("--gossfile %s", p.config.GossFile)
}
var errs *packer.MultiError
if p.config.Format != "" {
valid := false
for _, candidate := range validFormats {
if p.config.Format == candidate {
valid = true
break
}
}
if !valid {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("Invalid format choice %s. Valid options: %v",
p.config.Format, validFormats))
}
}
if p.config.FormatOptions != "" {
valid := false
for _, candidate := range validFormatOptions {
if p.config.FormatOptions == candidate {
valid = true
break
}
}
if !valid {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("Invalid format options choice %s. Valid options: %v",
p.config.FormatOptions, validFormatOptions))
}
}
if len(p.config.Tests) == 0 {
errs = packer.MultiErrorAppend(errs,
errors.New("tests must be specified"))
}
for _, path := range p.config.Tests {
if _, err := os.Stat(path); err != nil {
errs = packer.MultiErrorAppend(errs,
fmt.Errorf("Bad test '%s': %s", path, err))
}
}
if errs != nil && len(errs.Errors) > 0 {
return errs
}
return nil
}
// Provision runs the Goss Provisioner
func (p *Provisioner) Provision(ctx context.Context, ui packer.Ui, comm packer.Communicator, generatedData map[string]interface{}) error {
ui.Say("Provisioning with Goss")
if !p.config.SkipInstall {
if err := p.installGoss(ui, comm); err != nil {
return fmt.Errorf("Error installing Goss: %s", err)
}
} else {
ui.Message("Skipping Goss installation")
}
ui.Say("Uploading goss tests...")
if err := p.createDir(ui, comm, p.config.RemotePath); err != nil {
return fmt.Errorf("Error creating remote directory: %s", err)
}
if p.config.VarsFile != "" {
vf, err := os.Stat(p.config.VarsFile)
if err != nil {
return fmt.Errorf("Error stating file: %s", err)
}
if vf.Mode().IsRegular() {
ui.Message(fmt.Sprintf("Uploading vars file %s", p.config.VarsFile))
varsDest := filepath.ToSlash(filepath.Join(p.config.RemotePath, filepath.Base(p.config.VarsFile)))
if err := p.uploadFile(ui, comm, varsDest, p.config.VarsFile); err != nil {
return fmt.Errorf("Error uploading vars file: %s", err)
}
}
}
if len(p.config.VarsInline) != 0 {
ui.Message(fmt.Sprintf("Inline variables are %s", p.inline_vars()))
}
if len(p.config.VarsEnv) != 0 {
ui.Message(fmt.Sprintf("Env variables are %s", p.envVars()))
}
for _, src := range p.config.Tests {
s, err := os.Stat(src)
if err != nil {
return fmt.Errorf("Error stating file: %s", err)
}
if s.Mode().IsRegular() {
ui.Message(fmt.Sprintf("Uploading %s", src))
dst := filepath.ToSlash(filepath.Join(p.config.RemotePath, filepath.Base(src)))
if err := p.uploadFile(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading goss test: %s", err)
}
} else if s.Mode().IsDir() {
ui.Message(fmt.Sprintf("Uploading Dir %s", src))
dst := filepath.ToSlash(filepath.Join(p.config.RemotePath, filepath.Base(src)))
if err := p.uploadDir(ui, comm, dst, src); err != nil {
return fmt.Errorf("Error uploading goss test: %s", err)
}
} else {
ui.Message(fmt.Sprintf("Ignoring %s... not a regular file", src))
}
}
ui.Say("\n\n\nRunning goss tests...")
if err := p.runGoss(ui, comm); err != nil {
return fmt.Errorf("Error running Goss: %s", err)
}
ui.Say("\n\n\nDownloading spec file and debug info")
if err := p.downloadSpecs(ui, comm); err != nil {
return err
}
return nil
}
// downloadSpecs downloads the Goss specs from the remote host to current working dir on local machine
func (p *Provisioner) downloadSpecs(ui packer.Ui, comm packer.Communicator) error {
ui.Message(fmt.Sprintf("Downloading Goss specs from, %s and %s to current dir", gossSpecFile, gossDebugSpecFile))
for _, file := range []string{gossSpecFile, gossDebugSpecFile} {
f, err := os.Create(file)
if err != nil {
return fmt.Errorf("Error opening: %s", err)
}
if err = comm.Download(file, f); err != nil {
_ = f.Close()
return fmt.Errorf("Error downloading %s: %s", file, err)
}
_ = f.Close()
}
return nil
}
// installGoss downloads the Goss binary on the remote host
func (p *Provisioner) installGoss(ui packer.Ui, comm packer.Communicator) error {
ui.Message(fmt.Sprintf("Installing Goss from, %s", p.config.URL))
ctx := context.TODO()
cmd := &packer.RemoteCmd{
// Fallback on wget if curl failed for any reason (such as not being installed)
Command: fmt.Sprintf(
"curl -L %s %s -o %s %s || wget %s %s -O %s %s",
p.sslFlag("curl"), p.userPass("curl"), p.config.DownloadPath, p.config.URL,
p.sslFlag("wget"), p.userPass("wget"), p.config.DownloadPath, p.config.URL),
}
ui.Message(fmt.Sprintf("Downloading Goss to %s", p.config.DownloadPath))
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return fmt.Errorf("Unable to download Goss: %s", err)
}
cmd = &packer.RemoteCmd{
Command: fmt.Sprintf("chmod 555 %s && %s --version", p.config.DownloadPath, p.config.DownloadPath),
}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return fmt.Errorf("Unable to install Goss: %s", err)
}
return nil
}
// runGoss makes test and render goss commands and passes them to executor func runGossCmd
func (p *Provisioner) runGoss(ui packer.Ui, comm packer.Communicator) error {
goss := fmt.Sprintf("%s", p.config.DownloadPath)
cmdMap := map[string]string{
"render": fmt.Sprintf("cd %s && %s %s %s %s %s render > %s",
p.config.RemotePath, p.envVars(), goss, p.config.GossFile,
p.vars(), p.inline_vars(), gossSpecFile,
),
"render debug": fmt.Sprintf("cd %s && %s %s %s %s %s render -d > %s",
p.config.RemotePath, p.envVars(), goss, p.config.GossFile,
p.vars(), p.inline_vars(), gossDebugSpecFile,
),
"validate": fmt.Sprintf("cd %s && %s %s %s %s %s %s validate --retry-timeout %s --sleep %s %s %s",
p.config.RemotePath, p.enableSudo(), p.envVars(), goss, p.config.GossFile,
p.vars(), p.inline_vars(), p.retryTimeout(), p.sleep(), p.format(), p.formatOptions(),
),
}
for message, cmd := range cmdMap {
ui.Say(fmt.Sprintf("Running GOSS %s command: %s", message, cmd))
err := p.runGossCmd(ui, comm, &packer.RemoteCmd{Command: cmd}, message)
if err != nil {
return err
}
}
return nil
}
// runGoss tests and render goss commands.
func (p *Provisioner) runGossCmd(ui packer.Ui, comm packer.Communicator, cmd *packer.RemoteCmd, message string) error {
ctx := context.TODO()
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
}
if cmd.ExitStatus() != 0 {
// Inspect mode is on. Report failure but don't fail.
if p.config.Inspect {
ui.Say(fmt.Sprintf("Goss %s failed", message))
ui.Say(fmt.Sprintf("Inpect mode on : proceeding without failing Packer"))
} else {
return fmt.Errorf("goss non-zero exit status")
}
} else {
ui.Say(fmt.Sprintf("Goss %s ran successfully", message))
}
return nil
}
func (p *Provisioner) retryTimeout() string {
if p.config.RetryTimeout == "" {
return "0s" // goss default
}
return p.config.RetryTimeout
}
func (p *Provisioner) sleep() string {
if p.config.Sleep == "" {
return "1s" // goss default
}
return p.config.Sleep
}
func (p *Provisioner) format() string {
if p.config.Format != "" {
return fmt.Sprintf("-f %s", p.config.Format)
}
return ""
}
func (p *Provisioner) formatOptions() string {
if p.config.FormatOptions != "" {
return fmt.Sprintf("-o %s", p.config.FormatOptions)
}
return ""
}
func (p *Provisioner) vars() string {
if p.config.VarsFile != "" {
return fmt.Sprintf("--vars %s", filepath.ToSlash(filepath.Join(p.config.RemotePath, filepath.Base(p.config.VarsFile))))
}
return ""
}
func (p *Provisioner) inline_vars() string {
if len(p.config.VarsInline) != 0 {
inlineVarsJson, err := json.Marshal(p.config.VarsInline)
if err == nil {
return fmt.Sprintf("--vars-inline '%s'", string(inlineVarsJson))
} else {
fmt.Errorf("Error converting inline vars to json string %v", err)
}
}
return ""
}
func (p *Provisioner) envVars() string {
var sb strings.Builder
for env_var, value := range p.config.VarsEnv {
sb.WriteString(fmt.Sprintf("%s=\"%s\" ", env_var, value))
}
return sb.String()
}
func (p *Provisioner) sslFlag(cmdType string) string {
if p.config.SkipSSLChk {
switch cmdType {
case "curl":
return "-k"
case "wget":
return "--no-check-certificate"
default:
return ""
}
}
return ""
}
// enable sudo if required
func (p *Provisioner) enableSudo() string {
if p.config.UseSudo {
return "sudo"
}
return ""
}
// Deal with curl & wget username and password
func (p *Provisioner) userPass(cmdType string) string {
if p.config.Username != "" {
switch cmdType {
case "curl":
if p.config.Password == "" {
return fmt.Sprintf("-u %s", p.config.Username)
}
return fmt.Sprintf("-u %s:%s", p.config.Username, p.config.Password)
case "wget":
if p.config.Password == "" {
return fmt.Sprintf("--user=%s", p.config.Username)
}
return fmt.Sprintf("--user=%s --password=%s", p.config.Username, p.config.Password)
default:
return ""
}
}
return ""
}
// createDir creates a directory on the remote server
func (p *Provisioner) createDir(ui packer.Ui, comm packer.Communicator, dir string) error {
ui.Message(fmt.Sprintf("Creating directory: %s", dir))
ctx := context.TODO()
cmd := &packer.RemoteCmd{
Command: fmt.Sprintf("mkdir -p '%s'", dir),
}
if err := cmd.RunWithUi(ctx, comm, ui); err != nil {
return err
}
if cmd.ExitStatus() != 0 {
return fmt.Errorf("non-zero exit status")
}
return nil
}
// uploadFile uploads a file
func (p *Provisioner) uploadFile(ui packer.Ui, comm packer.Communicator, dst, src string) error {
f, err := os.Open(src)
if err != nil {
return fmt.Errorf("Error opening: %s", err)
}
defer f.Close()
if err = comm.Upload(dst, f, nil); err != nil {
return fmt.Errorf("Error uploading %s: %s", src, err)
}
return nil
}
// uploadDir uploads a directory
func (p *Provisioner) uploadDir(ui packer.Ui, comm packer.Communicator, dst, src string) error {
var ignore []string
if err := p.createDir(ui, comm, dst); err != nil {
return err
}
if src[len(src)-1] != '/' {
src = src + "/"
}
return comm.UploadDir(dst, src, ignore)
}