-
-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathpacker.go
More file actions
305 lines (266 loc) · 10.5 KB
/
packer.go
File metadata and controls
305 lines (266 loc) · 10.5 KB
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
package exec
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
errUtils "github.com/cloudposse/atmos/errors"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/dependencies"
log "github.com/cloudposse/atmos/pkg/logger"
"github.com/cloudposse/atmos/pkg/perf"
provSource "github.com/cloudposse/atmos/pkg/provisioner/source"
provWorkdir "github.com/cloudposse/atmos/pkg/provisioner/workdir"
"github.com/cloudposse/atmos/pkg/schema"
tfgenerate "github.com/cloudposse/atmos/pkg/terraform/generate"
u "github.com/cloudposse/atmos/pkg/utils"
)
// PackerFlags represents Packer command-line flags passed to ExecutePacker and ExecutePackerOutput.
type PackerFlags struct {
// Template specifies the Packer template file or directory path.
// If empty, defaults to "." (component working directory), which tells Packer to load all *.pkr.hcl files.
// Can be set via --template/-t flag or settings.packer.template in stack manifest.
Template string
// Query specifies a YQ expression to extract data from the Packer manifest.
// Used by ExecutePackerOutput to query the manifest.json file.
// Can be set via --query/-q flag.
Query string
}
// ExecutePacker executes Packer commands.
func ExecutePacker(
info *schema.ConfigAndStacksInfo,
packerFlags *PackerFlags,
) error {
defer perf.Track(nil, "exec.ExecutePacker")()
atmosConfig, err := cfg.InitCliConfig(*info, true)
if err != nil {
return err
}
// Validate packer configuration.
if err := checkPackerConfig(&atmosConfig); err != nil {
return err
}
// Add the `command` from `components.packer.command` from `atmos.yaml`.
if info.Command == "" {
if atmosConfig.Components.Packer.Command != "" {
info.Command = atmosConfig.Components.Packer.Command
} else {
info.Command = cfg.PackerComponentType
}
}
if info.SubCommand == "version" {
return ExecuteShellCommand(
atmosConfig,
info.Command,
[]string{info.SubCommand},
"",
nil,
false,
info.RedirectStdErr,
)
}
*info, err = ProcessStacks(&atmosConfig, *info, true, true, true, nil, nil)
if err != nil {
return err
}
if len(info.Stack) < 1 {
return errUtils.ErrMissingStack
}
if !info.ComponentIsEnabled {
log.Info("Component is not enabled and skipped", "component", info.ComponentFromArg)
return nil
}
// Check if the component exists as a Packer component.
componentPath, err := u.GetComponentPath(&atmosConfig, "packer", info.ComponentFolderPrefix, info.FinalComponent)
if err != nil {
return fmt.Errorf("failed to resolve component path: %w", err)
}
// Auto-generate files BEFORE path validation when the following conditions hold.
// 1. auto_generate_files is enabled.
// 2. Component has a generate section.
// 3. Not in dry-run mode (to avoid filesystem modifications).
// This allows generating entire components from stack configuration.
if atmosConfig.Components.Packer.AutoGenerateFiles && !info.DryRun { //nolint:nestif
generateSection := tfgenerate.GetGenerateSectionFromComponent(info.ComponentSection)
if generateSection != nil {
// Ensure component directory exists for file generation.
if mkdirErr := os.MkdirAll(componentPath, 0o755); mkdirErr != nil { //nolint:revive
return errors.Join(errUtils.ErrCreateDirectory, fmt.Errorf("auto-generation: %w", mkdirErr))
}
// Generate files before path validation.
if genErr := generateFilesForComponent(&atmosConfig, info, componentPath); genErr != nil {
return errors.Join(errUtils.ErrFileOperation, genErr)
}
}
}
componentPathExists, err := u.IsDirectory(componentPath)
if err != nil || !componentPathExists {
// Check if component has source configured for JIT provisioning.
if provSource.HasSource(info.ComponentSection) {
// Run JIT source provisioning before path validation.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
if err := provSource.AutoProvisionSource(ctx, &atmosConfig, cfg.PackerComponentType, info.ComponentSection, info.AuthContext); err != nil {
return fmt.Errorf("failed to auto-provision component source: %w", err)
}
// Check if source provisioner set a workdir path (source + workdir case).
// If so, use that path instead of the component path.
if workdirPath, ok := info.ComponentSection[provWorkdir.WorkdirPathKey].(string); ok {
componentPath = workdirPath
componentPathExists = true
err = nil // Clear any previous error since we have a valid workdir path.
} else {
// Re-check if component path now exists after provisioning (source only case).
componentPathExists, err = u.IsDirectory(componentPath)
}
}
// If still doesn't exist, return the error.
if err != nil || !componentPathExists {
// Get the base path for the error message, respecting the user's actual config.
basePath, _ := u.GetComponentBasePath(&atmosConfig, "packer")
return fmt.Errorf("%w: '%s' points to the Packer component '%s', but it does not exist in '%s'",
errUtils.ErrInvalidComponent,
info.ComponentFromArg,
info.FinalComponent,
basePath,
)
}
}
// Check if the component is allowed to be provisioned (`metadata.type` attribute).
// For Packer, only `build` creates external resources (AMIs, images, etc.).
// Other commands (init, validate, inspect, fmt, console) are read-only or local operations.
if info.ComponentIsAbstract && info.SubCommand == "build" {
return fmt.Errorf("%w: the component '%s' cannot be provisioned because it's marked as abstract (metadata.type: abstract)",
errUtils.ErrAbstractComponentCantBeProvisioned,
filepath.Join(info.ComponentFolderPrefix, info.Component))
}
// Check if the component is locked (`metadata.locked` is set to true).
if info.ComponentIsLocked && info.SubCommand == "build" {
return fmt.Errorf("%w: component '%s' cannot be modified (metadata.locked: true)",
errUtils.ErrLockedComponentCantBeProvisioned,
filepath.Join(info.ComponentFolderPrefix, info.Component))
}
// Resolve and install component dependencies.
resolver := dependencies.NewResolver(&atmosConfig)
deps, err := resolver.ResolveComponentDependencies("packer", info.StackSection, info.ComponentSection)
if err != nil {
return fmt.Errorf("failed to resolve component dependencies: %w", err)
}
if len(deps) > 0 {
log.Debug("Installing component dependencies", "component", info.ComponentFromArg, "stack", info.Stack, "tools", deps)
installer := dependencies.NewInstaller(&atmosConfig)
if err := installer.EnsureTools(deps); err != nil {
return fmt.Errorf("failed to install component dependencies: %w", err)
}
// Build PATH with toolchain binaries and add to component environment.
// This does NOT modify the global process environment - only the subprocess environment.
toolchainPATH, err := dependencies.BuildToolchainPATH(&atmosConfig, deps)
if err != nil {
return fmt.Errorf("failed to build toolchain PATH: %w", err)
}
// Propagate toolchain PATH into environment for subprocess.
info.ComponentEnvList = append(info.ComponentEnvList, fmt.Sprintf("PATH=%s", toolchainPATH))
}
// Check if the component 'settings.validation' section is specified and validate the component.
valid, err := ValidateComponent(
&atmosConfig,
info.ComponentFromArg,
info.ComponentSection,
"",
"",
nil,
0,
)
if err != nil {
return err
}
if !valid {
return fmt.Errorf("%w: the component '%s' did not pass the validation policies",
errUtils.ErrInvalidComponent,
info.ComponentFromArg,
)
}
// Find Packer template.
// It can be specified in the `settings.packer.template` section in the Atmos component manifest,
// or on the command line via the flag `--template <template> (shorthand `-t`)`.
template := packerFlags.Template
if template == "" {
packerSettingTemplate, err := GetPackerTemplateFromSettings(&info.ComponentSettingsSection)
if err != nil {
return err
}
if packerSettingTemplate != "" {
template = packerSettingTemplate
}
}
// If no template specified, default to "." (component working directory).
// Packer will load all *.pkr.hcl files from the component directory.
// This allows users to organize Packer configurations across multiple files.
// For example: variables.pkr.hcl, main.pkr.hcl, locals.pkr.hcl.
if template == "" {
template = "."
}
// Print component variables.
log.Debug("Variables for component in stack", "component", info.ComponentFromArg, "stack", info.Stack, "variables", info.ComponentVarsSection)
// Write variables to a file.
varFile := constructPackerComponentVarfileName(info)
varFilePath := constructPackerComponentVarfilePath(&atmosConfig, info)
log.Debug("Writing the variables to file", "file", varFilePath)
if !info.DryRun {
err = u.WriteToFileAsJSON(varFilePath, info.ComponentVarsSection, 0o644)
if err != nil {
return err
}
// Defer cleanup of the variable file.
// Use a closure to capture varFilePath and ensure cleanup runs even on early errors.
defer func() {
if removeErr := os.Remove(varFilePath); removeErr != nil && !os.IsNotExist(removeErr) {
log.Trace("Failed to remove var file during cleanup", "error", removeErr, "file", varFilePath)
}
}()
}
var inheritance string
if len(info.ComponentInheritanceChain) > 0 {
inheritance = info.ComponentFromArg + " -> " + strings.Join(info.ComponentInheritanceChain, " -> ")
}
workingDir := constructPackerComponentWorkingDir(&atmosConfig, info)
log.Debug("Packer context",
"executable", info.Command,
"command", info.SubCommand,
"atmos component", info.ComponentFromArg,
"atmos stack", info.StackFromArg,
"packer component", info.BaseComponentPath,
"packer template", template,
"working directory", workingDir,
"inheritance", inheritance,
"arguments and flags", info.AdditionalArgsAndFlags,
)
// Prepare arguments and flags.
allArgsAndFlags := []string{}
allArgsAndFlags = append(allArgsAndFlags, info.SubCommand)
allArgsAndFlags = append(allArgsAndFlags, []string{"-var-file", varFile}...)
allArgsAndFlags = append(allArgsAndFlags, info.AdditionalArgsAndFlags...)
allArgsAndFlags = append(allArgsAndFlags, template)
// Convert ComponentEnvSection to ComponentEnvList.
ConvertComponentEnvSectionToList(info)
// Prepare ENV vars.
envVars := append(info.ComponentEnvList, fmt.Sprintf("ATMOS_CLI_CONFIG_PATH=%s", atmosConfig.CliConfigPath))
basePath, err := filepath.Abs(atmosConfig.BasePath)
if err != nil {
return err
}
envVars = append(envVars, fmt.Sprintf("ATMOS_BASE_PATH=%s", basePath))
log.Debug("Using ENV", "variables", envVars)
return ExecuteShellCommand(
atmosConfig,
info.Command,
allArgsAndFlags,
componentPath,
envVars,
info.DryRun,
info.RedirectStdErr,
)
}