-
-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathhelmfile.go
More file actions
419 lines (361 loc) · 13.7 KB
/
helmfile.go
File metadata and controls
419 lines (361 loc) · 13.7 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
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
// https://github.com/roboll/helmfile#cli-reference
package exec
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"time"
"github.com/spf13/cobra"
errUtils "github.com/cloudposse/atmos/errors"
cfg "github.com/cloudposse/atmos/pkg/config"
"github.com/cloudposse/atmos/pkg/dependencies"
"github.com/cloudposse/atmos/pkg/helmfile"
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"
)
const (
// ComponentTypeHelmfile is the component type identifier for helmfile.
componentTypeHelmfile = "helmfile"
// Log key constants.
logKeyCluster = "cluster"
)
// ExecuteHelmfileCmd parses the provided arguments and flags and executes helmfile commands.
func ExecuteHelmfileCmd(cmd *cobra.Command, args []string, additionalArgsAndFlags []string) error {
info, err := ProcessCommandLineArgs(componentTypeHelmfile, cmd, args, additionalArgsAndFlags)
if err != nil {
return err
}
return ExecuteHelmfile(info)
}
// ExecuteHelmfile executes helmfile commands.
func ExecuteHelmfile(info schema.ConfigAndStacksInfo) error {
defer perf.Track(nil, "exec.ExecuteHelmfile")()
atmosConfig, err := cfg.InitCliConfig(info, true)
if err != nil {
return err
}
// Add the `command` from `components.helmfile.command` from `atmos.yaml`.
if info.Command == "" {
if atmosConfig.Components.Helmfile.Command != "" {
info.Command = atmosConfig.Components.Helmfile.Command
} else {
info.Command = cfg.HelmfileComponentType
}
}
if info.SubCommand == "version" {
tenv, err := dependencies.ForComponent(&atmosConfig, componentTypeHelmfile, nil, nil)
if err != nil {
return err
}
return ExecuteShellCommand(
atmosConfig,
tenv.Resolve(info.Command),
[]string{info.SubCommand},
"",
tenv.EnvVars(),
false,
info.RedirectStdErr,
)
}
info, err = ProcessStacks(&atmosConfig, info, true, true, true, nil, nil)
if err != nil {
return err
}
if !info.ComponentIsEnabled {
log.Info("Component is not enabled and skipped", "component", info.ComponentFromArg)
return nil
}
err = checkHelmfileConfig(&atmosConfig)
if err != nil {
return err
}
// Check if the component exists as a helmfile component.
componentPath, err := u.GetComponentPath(&atmosConfig, componentTypeHelmfile, 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.Helmfile.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.HelmfileComponentType, 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, componentTypeHelmfile)
return fmt.Errorf("%w: '%s' points to the Helmfile 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).
if (info.SubCommand == "sync" || info.SubCommand == "apply" || info.SubCommand == "deploy") && info.ComponentIsAbstract {
return fmt.Errorf("abstract component '%s' cannot be provisioned since it's explicitly prohibited from being deployed "+
"by 'metadata.type: abstract' attribute", filepath.Join(info.ComponentFolderPrefix, info.Component))
}
// Check if the component is locked (`metadata.locked` is set to true).
if info.ComponentIsLocked {
// Allow read-only commands, block modification commands.
switch info.SubCommand {
case "sync", "apply", "deploy", "delete", "destroy":
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.
tenv, err := dependencies.ForComponent(&atmosConfig, componentTypeHelmfile, info.StackSection, info.ComponentSection)
if err != nil {
return err
}
info.ComponentEnvList = append(info.ComponentEnvList, tenv.EnvVars()...)
// Print component variables.
log.Debug("Variables for component in stack", "component", info.ComponentFromArg, "stack", info.Stack, "variables", info.ComponentVarsSection)
// 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,
)
}
// Write variables to a file.
varFile := constructHelmfileComponentVarfileName(&info)
varFilePath := constructHelmfileComponentVarfilePath(&atmosConfig, &info)
log.Debug("Writing the variables to file:", "file", varFilePath)
if !info.DryRun {
err = u.WriteToFileAsYAML(varFilePath, info.ComponentVarsSection, 0o644)
if err != nil {
return err
}
}
// Handle `helmfile deploy` custom command.
if info.SubCommand == "deploy" {
info.SubCommand = "sync"
}
context := cfg.GetContextFromVars(info.ComponentVarsSection)
envVarsEKS := []string{}
if atmosConfig.Components.Helmfile.UseEKS {
// Resolve cluster name using the helmfile package.
clusterInput := helmfile.ClusterNameInput{
FlagValue: info.ClusterName,
ConfigValue: atmosConfig.Components.Helmfile.ClusterName,
Template: atmosConfig.Components.Helmfile.ClusterNameTemplate,
Pattern: atmosConfig.Components.Helmfile.ClusterNamePattern,
}
clusterResult, err := helmfile.ResolveClusterName(
clusterInput,
&context,
&atmosConfig,
info.ComponentSection,
ProcessTmpl,
)
if err != nil {
return err
}
clusterName := clusterResult.ClusterName
if clusterResult.IsDeprecated {
log.Warn("cluster_name_pattern is deprecated, use cluster_name_template with Go template syntax instead")
}
log.Debug("Using cluster name", logKeyCluster, clusterName, "source", clusterResult.Source)
// Resolve AWS auth using the helmfile package.
authInput := helmfile.AuthInput{
Identity: info.Identity,
ProfilePattern: atmosConfig.Components.Helmfile.HelmAwsProfilePattern,
}
authResult, err := helmfile.ResolveAWSAuth(authInput, &context)
if err != nil {
return err
}
useIdentityAuth := authResult.UseIdentityAuth
helmAwsProfile := authResult.Profile
if authResult.IsDeprecated {
log.Warn("helm_aws_profile_pattern is deprecated, use --identity flag instead")
}
log.Debug("Using AWS auth", "source", authResult.Source, "useIdentity", useIdentityAuth)
// Download kubeconfig by running `aws eks update-kubeconfig`.
kubeconfigPath := filepath.Join(atmosConfig.Components.Helmfile.KubeconfigPath, info.ContextPrefix+"-kubecfg")
log.Debug("Downloading and saving kubeconfig", logKeyCluster, clusterName, "path", kubeconfigPath)
// Build aws eks update-kubeconfig command args.
awsArgs := []string{
"eks",
"update-kubeconfig",
fmt.Sprintf("--name=%s", clusterName),
fmt.Sprintf("--region=%s", context.Region),
fmt.Sprintf("--kubeconfig=%s", kubeconfigPath),
}
// Add profile flag if using deprecated profile pattern (not identity auth).
if !useIdentityAuth && helmAwsProfile != "" {
awsArgs = append([]string{"--profile", helmAwsProfile}, awsArgs...)
}
err = ExecuteShellCommand(
atmosConfig,
tenv.Resolve("aws"),
awsArgs,
componentPath,
tenv.EnvVars(),
info.DryRun,
info.RedirectStdErr,
)
if err != nil {
return err
}
// Set environment variables for helmfile execution.
if !useIdentityAuth && helmAwsProfile != "" {
envVarsEKS = append(envVarsEKS, fmt.Sprintf("AWS_PROFILE=%s", helmAwsProfile))
}
envVarsEKS = append(envVarsEKS, fmt.Sprintf("KUBECONFIG=%s", kubeconfigPath))
}
// Print command info.
log.Debug("Command info:")
log.Debug("Helmfile binary: " + info.Command)
log.Debug("Helmfile command: " + info.SubCommand)
// https://github.com/roboll/helmfile#cli-reference
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace=test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options "--no-color --namespace test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace=test"
// atmos helmfile diff echo-server -s tenant1-ue2-dev --global-options="--no-color --namespace test"
log.Debug("Global", "options", info.GlobalOptions)
log.Debug("Arguments and flags", "additional", info.AdditionalArgsAndFlags)
log.Debug("Component: " + info.ComponentFromArg)
if len(info.BaseComponent) > 0 {
log.Debug("Helmfile component: " + info.BaseComponent)
}
if info.Stack == info.StackFromArg {
log.Debug("Stack: " + info.StackFromArg)
} else {
log.Debug("Stack: " + info.StackFromArg)
log.Debug("Stack path: " + filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath, info.Stack))
}
workingDir := constructHelmfileComponentWorkingDir(&atmosConfig, &info)
log.Debug("Using", "working dir", workingDir)
// Prepare arguments and flags.
allArgsAndFlags := []string{"--state-values-file", varFile}
if info.GlobalOptions != nil && len(info.GlobalOptions) > 0 {
allArgsAndFlags = append(allArgsAndFlags, info.GlobalOptions...)
}
allArgsAndFlags = append(allArgsAndFlags, info.SubCommand)
allArgsAndFlags = append(allArgsAndFlags, info.AdditionalArgsAndFlags...)
// Convert ComponentEnvSection to ComponentEnvList.
// ComponentEnvSection is populated by auth hooks and stack config env sections.
for k, v := range info.ComponentEnvSection {
info.ComponentEnvList = append(info.ComponentEnvList, fmt.Sprintf("%s=%v", k, v))
}
// Prepare ENV vars.
envVars := append(info.ComponentEnvList, []string{
fmt.Sprintf("STACK=%s", info.Stack),
}...)
// Append the context ENV vars (first check if they are not set by the caller).
env := os.Getenv("NAMESPACE")
if env == "" {
envVars = append(envVars, fmt.Sprintf("NAMESPACE=%s", context.Namespace))
}
env = os.Getenv("TENANT")
if env == "" {
envVars = append(envVars, fmt.Sprintf("TENANT=%s", context.Tenant))
}
env = os.Getenv("ENVIRONMENT")
if env == "" {
envVars = append(envVars, fmt.Sprintf("ENVIRONMENT=%s", context.Environment))
}
env = os.Getenv("STAGE")
if env == "" {
envVars = append(envVars, fmt.Sprintf("STAGE=%s", context.Stage))
}
env = os.Getenv("REGION")
if env == "" {
envVars = append(envVars, fmt.Sprintf("REGION=%s", context.Region))
}
// Set KUBECONFIG: When UseEKS is true, the EKS-specific kubeconfig (from envVarsEKS)
// takes precedence over the general KubeconfigPath setting.
if atmosConfig.Components.Helmfile.KubeconfigPath != "" && !atmosConfig.Components.Helmfile.UseEKS {
envVars = append(envVars, fmt.Sprintf("KUBECONFIG=%s", atmosConfig.Components.Helmfile.KubeconfigPath))
}
if atmosConfig.Components.Helmfile.UseEKS {
envVars = append(envVars, envVarsEKS...)
}
envVars = append(envVars, 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 vars:")
for _, v := range envVars {
log.Debug(v)
}
err = ExecuteShellCommand(
atmosConfig,
info.Command,
allArgsAndFlags,
componentPath,
envVars,
info.DryRun,
info.RedirectStdErr,
WithEnvironment(info.SanitizedEnv),
)
if err != nil {
return err
}
// Cleanup.
err = os.Remove(varFilePath)
if err != nil {
log.Warn(err.Error())
}
return nil
}