-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
packer.go
248 lines (210 loc) · 8.61 KB
/
packer.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
// Package packer allows to interact with Packer.
package packer
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"sync"
"time"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/hashicorp/go-multierror"
"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/shell"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/hashicorp/go-version"
)
// PackerPluginPathEnvVar is the built-in env variable defining where plugins are downloaded
const PackerPluginPathEnvVar = "PACKER_PLUGIN_PATH"
// Options are the options for Packer.
type Options struct {
Template string // The path to the Packer template
Vars map[string]string // The custom vars to pass when running the build command
VarFiles []string // Var file paths to pass Packer using -var-file option
Only string // If specified, only run the build of this name
Except string // Runs the build excluding the specified builds and post-processors
Env map[string]string // Custom environment variables to set when running Packer
RetryableErrors map[string]string // If packer build fails with one of these (transient) errors, retry. The keys are a regexp to match against the error and the message is what to display to a user if that error is matched.
MaxRetries int // Maximum number of times to retry errors matching RetryableErrors
TimeBetweenRetries time.Duration // The amount of time to wait between retries
WorkingDir string // The directory to run packer in
Logger *logger.Logger // If set, use a non-default logger
DisableTemporaryPluginPath bool // If set, do not use a temporary directory for Packer plugins.
}
// BuildArtifacts can take a map of identifierName <-> Options and then parallelize
// the packer builds. Once all the packer builds have completed a map of identifierName <-> generated identifier
// is returned. The identifierName can be anything you want, it is only used so that you can
// know which generated artifact is which.
func BuildArtifacts(t testing.TestingT, artifactNameToOptions map[string]*Options) map[string]string {
result, err := BuildArtifactsE(t, artifactNameToOptions)
if err != nil {
t.Fatalf("Error building artifacts: %s", err.Error())
}
return result
}
// BuildArtifactsE can take a map of identifierName <-> Options and then parallelize
// the packer builds. Once all the packer builds have completed a map of identifierName <-> generated identifier
// is returned. If any artifact fails to build, the errors are accumulated and returned
// as a MultiError. The identifierName can be anything you want, it is only used so that you can
// know which generated artifact is which.
func BuildArtifactsE(t testing.TestingT, artifactNameToOptions map[string]*Options) (map[string]string, error) {
var waitForArtifacts sync.WaitGroup
waitForArtifacts.Add(len(artifactNameToOptions))
var artifactNameToArtifactId = map[string]string{}
var errorsOccurred = new(multierror.Error)
for artifactName, curOptions := range artifactNameToOptions {
// The following is necessary to make sure artifactName and curOptions don't
// get updated due to concurrency within the scope of t.Run(..) below
artifactName := artifactName
curOptions := curOptions
go func() {
defer waitForArtifacts.Done()
artifactId, err := BuildArtifactE(t, curOptions)
if err != nil {
errorsOccurred = multierror.Append(errorsOccurred, err)
} else {
artifactNameToArtifactId[artifactName] = artifactId
}
}()
}
waitForArtifacts.Wait()
return artifactNameToArtifactId, errorsOccurred.ErrorOrNil()
}
// BuildArtifact builds the given Packer template and return the generated Artifact ID.
func BuildArtifact(t testing.TestingT, options *Options) string {
artifactID, err := BuildArtifactE(t, options)
if err != nil {
t.Fatal(err)
}
return artifactID
}
// BuildArtifactE builds the given Packer template and return the generated Artifact ID.
func BuildArtifactE(t testing.TestingT, options *Options) (string, error) {
options.Logger.Logf(t, "Running Packer to generate a custom artifact for template %s", options.Template)
if !options.DisableTemporaryPluginPath {
options.Logger.Logf(t, "Creating a temporary directory for Packer plugins")
pluginDir, err := ioutil.TempDir("", "terratest-packer-")
if err != nil {
log.Fatal(err)
}
if len(options.Env) == 0 {
options.Env = make(map[string]string)
}
options.Env[PackerPluginPathEnvVar] = pluginDir
defer os.RemoveAll(pluginDir)
}
err := packerInit(t, options)
if err != nil {
return "", err
}
cmd := shell.Command{
Command: "packer",
Args: formatPackerArgs(options),
Env: options.Env,
WorkingDir: options.WorkingDir,
}
description := fmt.Sprintf("%s %v", cmd.Command, cmd.Args)
output, err := retry.DoWithRetryableErrorsE(t, description, options.RetryableErrors, options.MaxRetries, options.TimeBetweenRetries, func() (string, error) {
return shell.RunCommandAndGetOutputE(t, cmd)
})
if err != nil {
return "", err
}
return extractArtifactID(output)
}
// BuildAmi builds the given Packer template and return the generated AMI ID.
//
// Deprecated: Use BuildArtifact instead.
func BuildAmi(t testing.TestingT, options *Options) string {
return BuildArtifact(t, options)
}
// BuildAmiE builds the given Packer template and return the generated AMI ID.
//
// Deprecated: Use BuildArtifactE instead.
func BuildAmiE(t testing.TestingT, options *Options) (string, error) {
return BuildArtifactE(t, options)
}
// The Packer machine-readable log output should contain an entry of this format:
//
// AWS: <timestamp>,<builder>,artifact,<index>,id,<region>:<image_id>
// GCP: <timestamp>,<builder>,artifact,<index>,id,<image_id>
//
// For example:
//
// 1456332887,amazon-ebs,artifact,0,id,us-east-1:ami-b481b3de
// 1533742764,googlecompute,artifact,0,id,terratest-packer-example-2018-08-08t15-35-19z
//
func extractArtifactID(packerLogOutput string) (string, error) {
re := regexp.MustCompile(`.+artifact,\d+?,id,(?:.+?:|)(.+)`)
matches := re.FindStringSubmatch(packerLogOutput)
if len(matches) == 2 {
return matches[1], nil
}
return "", errors.New("Could not find Artifact ID pattern in Packer output")
}
// packerInit checks if init is supported in the current version of Packer, then runs packer init to download any required plugins.
func packerInit(t testing.TestingT, options *Options) error {
// The init command was introduced in Packer 1.7.0
const packerInitVersion = "1.7.0"
minInitVersion, err := version.NewVersion(packerInitVersion)
if err != nil {
return err
}
cmd := shell.Command{
Command: "packer",
Args: []string{"-version"},
Env: options.Env,
WorkingDir: options.WorkingDir,
}
description := fmt.Sprintf("%s %v", cmd.Command, cmd.Args)
installedVersion, err := retry.DoWithRetryableErrorsE(t, description, options.RetryableErrors, options.MaxRetries, options.TimeBetweenRetries, func() (string, error) {
return shell.RunCommandAndGetOutputE(t, cmd)
})
if err != nil {
return err
}
thisVersion, err := version.NewVersion(installedVersion)
if err != nil {
return err
}
if thisVersion.LessThan(minInitVersion) {
options.Logger.Logf(t, "Skipping 'packer init' because it is not present in this version (%s)", thisVersion)
return nil
}
options.Logger.Logf(t, "Running Packer init")
cmd = shell.Command{
Command: "packer",
Args: []string{"init", options.Template},
Env: options.Env,
WorkingDir: options.WorkingDir,
}
description = fmt.Sprintf("%s %v", cmd.Command, cmd.Args)
_, err = retry.DoWithRetryableErrorsE(t, description, options.RetryableErrors, options.MaxRetries, options.TimeBetweenRetries, func() (string, error) {
return shell.RunCommandAndGetOutputE(t, cmd)
})
if err != nil {
return err
}
return nil
}
// Convert the inputs to a format palatable to packer. The build command should have the format:
//
// packer build [OPTIONS] template
func formatPackerArgs(options *Options) []string {
args := []string{"build", "-machine-readable"}
for key, value := range options.Vars {
args = append(args, "-var", fmt.Sprintf("%s=%s", key, value))
}
for _, filePath := range options.VarFiles {
args = append(args, "-var-file", filePath)
}
if options.Only != "" {
args = append(args, fmt.Sprintf("-only=%s", options.Only))
}
if options.Except != "" {
args = append(args, fmt.Sprintf("-except=%s", options.Except))
}
return append(args, options.Template)
}