-
-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathstack_processor_utils.go
More file actions
2108 lines (1866 loc) · 80.3 KB
/
stack_processor_utils.go
File metadata and controls
2108 lines (1866 loc) · 80.3 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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package exec
import (
"encoding/json"
stderrors "errors"
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"sync"
"github.com/go-viper/mapstructure/v2"
"github.com/pkg/errors"
"github.com/santhosh-tekuri/jsonschema/v5"
"gopkg.in/yaml.v3"
errUtils "github.com/cloudposse/atmos/errors"
cfg "github.com/cloudposse/atmos/pkg/config"
log "github.com/cloudposse/atmos/pkg/logger"
m "github.com/cloudposse/atmos/pkg/merge"
"github.com/cloudposse/atmos/pkg/perf"
"github.com/cloudposse/atmos/pkg/schema"
u "github.com/cloudposse/atmos/pkg/utils"
)
// Mutex to serialize writes to importsConfig maps during parallel import processing.
var importsConfigLock = &sync.Mutex{}
// extractLocalsResult holds the results of parsing raw YAML and extracting locals.
type extractLocalsResult struct {
locals map[string]any // Resolved locals.
settings map[string]any // Settings section (for template context).
vars map[string]any // Vars section (for template context).
env map[string]any // Env section (for template context).
hasLocals bool // Whether any locals section exists in the file (including empty locals).
}
// extractLocalsFromRawYAML parses raw YAML content and extracts/resolves file-scoped locals.
// This function is called BEFORE template processing to make locals available during template execution.
// The raw YAML may contain unresolved templates like {{ .locals.X }}, which YAML treats as strings.
// The locals resolver handles resolving self-references between locals.
// Returns the resolved locals and other sections (settings, vars, env) that should be available during template processing.
//
// Locals are extracted and merged in order of specificity:
// 1. Global locals (root level)
// 2. Section-specific locals (terraform, helmfile, packer sections)
//
// Section-specific locals inherit from and can override global locals.
// All resolved locals are flattened into a single map for template processing.
func extractLocalsFromRawYAML(atmosConfig *schema.AtmosConfiguration, yamlContent string, filePath string) (*extractLocalsResult, error) {
defer perf.Track(atmosConfig, "exec.extractLocalsFromRawYAML")()
// Parse raw YAML to extract the structure.
// YAML treats template expressions like {{ .locals.X }} as plain strings,
// so parsing succeeds even with unresolved templates.
// Use Atmos's YAML unmarshaling which properly handles custom tags like !terraform.state
// by converting them to strings (e.g., "!terraform.state component .output").
// Create a default config if nil (UnmarshalYAMLFromFile requires non-nil config).
configToUse := atmosConfig
if configToUse == nil {
configToUse = &schema.AtmosConfiguration{}
}
rawConfig, err := u.UnmarshalYAMLFromFile[map[string]any](configToUse, yamlContent, filePath)
if err != nil {
// Provide a helpful hint if the file might contain Go template directives
// that aren't valid YAML. Files with .yaml.tmpl extension are processed
// as templates first, which allows non-YAML-valid Go template syntax.
hint := ""
if !strings.HasSuffix(filePath, u.TemplateExtension) {
hint = " (hint: if this file contains Go template directives, rename it to .yaml.tmpl)"
}
return nil, fmt.Errorf("%w: failed to parse YAML for locals extraction%s: %w", errUtils.ErrInvalidStackManifest, hint, err)
}
if rawConfig == nil {
return &extractLocalsResult{}, nil
}
// Derive the stack name from the file path so that YAML functions like
// !terraform.state (2-arg form) can resolve their implicit stack reference.
// Previously, an empty string was passed here, which caused !terraform.state
// to fail with "stack is required" (see GitHub issue #2080).
currentStack := deriveStackNameForLocals(atmosConfig, rawConfig, filePath)
localsCtx, err := ProcessStackLocals(atmosConfig, rawConfig, filePath, currentStack)
if err != nil {
return nil, fmt.Errorf("%w: failed to process stack locals: %w", errUtils.ErrInvalidStackManifest, err)
}
return buildLocalsResult(rawConfig, localsCtx), nil
}
// deriveStackNameForLocals derives the stack name from the file path and raw config
// so that YAML functions in locals (like !terraform.state) can use stack context.
// This uses the same logic as describe_locals.go (deriveStackName) to compute the
// stack name from the file path, vars section, and atmos config.
// Returns empty string if the stack name cannot be determined.
func deriveStackNameForLocals(atmosConfig *schema.AtmosConfiguration, rawConfig map[string]any, filePath string) string {
if atmosConfig == nil {
return ""
}
// Extract vars section for stack name derivation.
var varsSection map[string]any
if vs, ok := rawConfig[cfg.VarsSectionName].(map[string]any); ok {
varsSection = vs
}
// Compute relative stack file name from file path.
stackFileName := computeStackFileName(atmosConfig, filePath)
if stackFileName == "" {
return ""
}
return deriveStackName(atmosConfig, stackFileName, varsSection, rawConfig)
}
// computeStackFileName computes the relative stack file name from an absolute file path
// by stripping the stacks base path prefix and the file extension.
// This produces a name like "deploy/dev" or "orgs/acme/plat/dev/us-east-1".
func computeStackFileName(atmosConfig *schema.AtmosConfiguration, filePath string) string {
if atmosConfig == nil {
return ""
}
// Get the absolute stacks base path.
stacksBasePath := filepath.Join(atmosConfig.BasePath, atmosConfig.Stacks.BasePath)
absStacksBasePath, err := filepath.Abs(stacksBasePath)
if err != nil {
return ""
}
absFilePath, err := filepath.Abs(filePath)
if err != nil {
return ""
}
// Strip the base path prefix.
rel, err := filepath.Rel(absStacksBasePath, absFilePath)
if err != nil {
return ""
}
// Remove known stack/template suffixes (longest first to handle .yaml.tmpl correctly).
for _, suffix := range []string{
u.YamlTemplateExtension, // .yaml.tmpl
u.YmlTemplateExtension, // .yml.tmpl
u.YamlFileExtension, // .yaml
u.YmlFileExtension, // .yml
} {
if strings.HasSuffix(rel, suffix) {
rel = strings.TrimSuffix(rel, suffix)
break
}
}
return rel
}
// buildLocalsResult builds an extractLocalsResult from raw config and resolved locals context.
func buildLocalsResult(rawConfig map[string]any, localsCtx *LocalsContext) *extractLocalsResult {
result := &extractLocalsResult{
locals: localsCtx.MergeForTemplateContext(),
}
// Detect locals section presence (including empty locals).
// This allows empty locals: {} to still enable template context.
if _, ok := rawConfig[cfg.LocalsSectionName]; ok {
result.hasLocals = true
}
if localsCtx.HasTerraformLocals || localsCtx.HasHelmfileLocals || localsCtx.HasPackerLocals {
result.hasLocals = true
}
// Ensure locals map is never nil when hasLocals is true.
if result.hasLocals && result.locals == nil {
result.locals = make(map[string]any)
}
// Extract settings, vars, env sections for template context.
if settings, ok := rawConfig[cfg.SettingsSectionName].(map[string]any); ok {
result.settings = settings
}
if vars, ok := rawConfig[cfg.VarsSectionName].(map[string]any); ok {
result.vars = vars
}
if env, ok := rawConfig[cfg.EnvSectionName].(map[string]any); ok {
result.env = env
}
return result
}
// processTemplatesInSection processes Go templates in a section (settings, vars, or env) using the provided context.
// This allows sections to reference resolved locals and other processed sections.
// Returns the processed section or an error if template processing fails.
// IMPORTANT: Uses ignoreMissingTemplateValues=false so that templates referencing values not in the
// current context (like {{ .atmos_component }}) will fail, and the caller can fall back to raw values.
// This preserves those templates for later processing when the full context is available.
func processTemplatesInSection(atmosConfig *schema.AtmosConfiguration, section map[string]any, context map[string]any, filePath string) (map[string]any, error) {
defer perf.Track(atmosConfig, "exec.processTemplatesInSection")()
if len(section) == 0 {
return section, nil
}
// Convert section to YAML for template processing.
yamlStr, err := u.ConvertToYAML(section)
if err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to convert section to YAML: %w", err))
}
// Quick check: if no template markers, return as-is.
if !strings.Contains(yamlStr, "{{") {
return section, nil
}
// Process templates in the YAML string.
// Use ignoreMissingTemplateValues=false so templates with missing values fail
// (e.g., {{ .atmos_component }} when component context isn't available yet).
// The caller will fall back to raw values, preserving templates for later processing.
processed, err := ProcessTmpl(atmosConfig, filePath, yamlStr, context, false)
if err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to process templates in section: %w", err))
}
// Parse the processed YAML back to a map.
var result map[string]any
if err := yaml.Unmarshal([]byte(processed), &result); err != nil {
return nil, stderrors.Join(errUtils.ErrInvalidStackManifest, fmt.Errorf("failed to parse processed section YAML: %w", err))
}
return result, nil
}
// extractAndAddLocalsToContext extracts locals from YAML and adds them to the template context.
// Returns the updated context and any error encountered during locals extraction.
// Note: The "locals" key in context is reserved for file-scoped locals and will override
// any user-provided "locals" key in the import context.
// Settings, vars, and env sections are also added to the context so templates can reference them.
// For template files (.tmpl), YAML parse errors are logged and the function continues
// without locals, since template files may contain Go template syntax that isn't valid YAML
// until after template processing.
func extractAndAddLocalsToContext(
atmosConfig *schema.AtmosConfiguration,
yamlContent string,
filePath string,
relativeFilePath string,
context map[string]any,
) (map[string]any, error) {
defer perf.Track(atmosConfig, "exec.extractAndAddLocalsToContext")()
// Enforce file-scoped locals: clear any inherited locals from parent context.
// Locals are file-scoped and should NOT inherit across file boundaries.
// This ensures that each file only has access to its own locals.
if context != nil {
delete(context, cfg.LocalsSectionName)
}
extractResult, localsErr := extractLocalsFromRawYAML(atmosConfig, yamlContent, filePath)
if localsErr != nil {
// For template files (.tmpl), YAML parse errors are expected since the raw content
// may contain Go template syntax that isn't valid YAML until after processing.
// Log the error and continue without locals - template processing will happen next.
if strings.HasSuffix(filePath, u.TemplateExtension) {
log.Trace("Skipping locals extraction for template file with invalid YAML", "file", relativeFilePath, "error", localsErr)
return context, nil
}
// Circular dependencies in locals are a stack misconfiguration error.
// Return a helpful error with hints on how to fix it.
if stderrors.Is(localsErr, errUtils.ErrLocalsCircularDep) {
return context, errUtils.Build(errUtils.ErrLocalsCircularDep).
WithCause(localsErr).
WithContext("file", relativeFilePath).
WithHintf("Fix the circular dependency in '%s'", relativeFilePath).
WithHint("Ensure locals don't reference each other in a cycle").
WithHintf("Use 'atmos describe locals --stack %s' to inspect locals", relativeFilePath).
WithExitCode(1).
Err()
}
return context, localsErr
}
// Only modify context if a locals section exists in the file.
// This preserves the original behavior where files without locals don't trigger
// template processing (see the len(context) > 0 check in ProcessBaseStackConfig).
// We check hasLocals instead of len(locals) to support empty locals: {} sections,
// which should still enable template context.
if !extractResult.hasLocals {
return context, nil
}
// Initialize context if nil.
if context == nil {
context = make(map[string]any)
}
// Add resolved locals to the template context first.
// This allows settings/vars/env templates to reference locals.
context[cfg.LocalsSectionName] = extractResult.locals
log.Trace("Extracted and resolved locals", "file", relativeFilePath, "count", len(extractResult.locals))
// Process templates in settings, vars, env sections using the resolved locals.
// This enables bidirectional references between locals and settings:
// locals:
// stage: dev
// settings:
// context:
// stage_from_local: '{{ .locals.stage }}' # Now resolves to "dev"
// vars:
// setting_value: '{{ .settings.context.stage_from_local }}' # Now resolves to "dev"
//
// Note: We need to process these sections AFTER locals are resolved so they can reference .locals,
// but BEFORE adding them to the context so vars can reference the resolved settings values.
// Seed section context with any external import context so that settings/vars/env
// templates referencing import-provided values can resolve during section processing.
// Locals are always overridden to ensure file-scoped locality.
localsOnlyContext := map[string]any{}
for k, v := range context {
localsOnlyContext[k] = v
}
localsOnlyContext[cfg.LocalsSectionName] = extractResult.locals
// Process templates in settings if it contains template expressions.
if extractResult.settings != nil {
processedSettings, err := processTemplatesInSection(atmosConfig, extractResult.settings, localsOnlyContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in settings section", "file", relativeFilePath, "error", err)
// Fall back to raw settings on error.
context[cfg.SettingsSectionName] = extractResult.settings
} else {
context[cfg.SettingsSectionName] = processedSettings
}
}
if extractResult.vars != nil {
// For vars, we need locals, external context, and processed settings available.
varsContext := map[string]any{}
for k, v := range localsOnlyContext {
varsContext[k] = v
}
if processedSettings, ok := context[cfg.SettingsSectionName].(map[string]any); ok {
varsContext[cfg.SettingsSectionName] = processedSettings
}
processedVars, err := processTemplatesInSection(atmosConfig, extractResult.vars, varsContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in vars section", "file", relativeFilePath, "error", err)
// Fall back to raw vars on error.
context[cfg.VarsSectionName] = extractResult.vars
} else {
context[cfg.VarsSectionName] = processedVars
}
}
if extractResult.env != nil {
// For env, we need locals, external context, processed settings, and processed vars.
envContext := map[string]any{}
for k, v := range localsOnlyContext {
envContext[k] = v
}
if processedSettings, ok := context[cfg.SettingsSectionName].(map[string]any); ok {
envContext[cfg.SettingsSectionName] = processedSettings
}
if processedVars, ok := context[cfg.VarsSectionName].(map[string]any); ok {
envContext[cfg.VarsSectionName] = processedVars
}
processedEnv, err := processTemplatesInSection(atmosConfig, extractResult.env, envContext, relativeFilePath)
if err != nil {
log.Debug("Failed to process templates in env section", "file", relativeFilePath, "error", err)
// Fall back to raw env on error.
context[cfg.EnvSectionName] = extractResult.env
} else {
context[cfg.EnvSectionName] = processedEnv
}
}
return context, nil
}
// stackProcessResult holds the result of processing a single stack in parallel.
type stackProcessResult struct {
index int
stackFileName string
yamlConfig string
finalConfig map[string]any
stackConfig map[string]any
importsConfig map[string]map[string]any
uniqueImports []string
mergeContext *m.MergeContext
err error
}
// ProcessYAMLConfigFiles takes a list of paths to stack manifests, processes and deep-merges all imports, and returns a list of stack configs.
func ProcessYAMLConfigFiles(
atmosConfig *schema.AtmosConfiguration,
stacksBasePath string,
terraformComponentsBasePath string,
helmfileComponentsBasePath string,
packerComponentsBasePath string,
ansibleComponentsBasePath string,
filePaths []string,
processStackDeps bool,
processComponentDeps bool,
ignoreMissingFiles bool,
) (
[]string,
map[string]any,
map[string]map[string]any,
error,
) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFiles")()
count := len(filePaths)
listResult := make([]string, count)
mapResult := make(map[string]any, count)
rawStackConfigs := make(map[string]map[string]any, count)
// Create channel for results - no locks needed with channels.
results := make(chan stackProcessResult, count)
var wg sync.WaitGroup
wg.Add(count)
for i, filePath := range filePaths {
go func(i int, p string) {
defer wg.Done()
stackBasePath := stacksBasePath
if len(stackBasePath) < 1 {
stackBasePath = filepath.Dir(p)
}
stackFileName := strings.TrimSuffix(
strings.TrimSuffix(
u.TrimBasePathFromPath(stackBasePath+"/", p),
u.DefaultStackConfigFileExtension),
".yml",
)
// Each goroutine gets its own merge context to avoid data races.
// For single-file operations (like describe component), use the
// SetLastMergeContext/GetLastMergeContext mechanism instead.
mergeContext := m.NewMergeContext()
if atmosConfig != nil && atmosConfig.TrackProvenance {
mergeContext.EnableProvenance()
}
deepMergedStackConfig, importsConfig, stackConfig, _, _, _, _, mergeContext, err := ProcessYAMLConfigFileWithContext(
atmosConfig,
stackBasePath,
p,
map[string]map[string]any{},
nil,
ignoreMissingFiles,
false,
atmosConfig != nil && atmosConfig.Templates.Settings.IgnoreMissingTemplateValues,
false,
map[string]any{},
map[string]any{},
map[string]any{},
map[string]any{},
"",
mergeContext,
)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
if mergeContext != nil {
if len(mergeContext.ImportChain) > 0 {
log.Trace("After processing file, merge context has import chain", "file", stackFileName, "import_chain_length", len(mergeContext.ImportChain), "import_chain", mergeContext.ImportChain)
} else {
log.Trace("After processing file, merge context has empty import chain", "file", stackFileName)
}
}
var imports []string
for k := range importsConfig {
imports = append(imports, k)
}
uniqueImports := u.UniqueStrings(imports)
sort.Strings(uniqueImports)
componentStackMap := map[string]map[string][]string{}
finalConfig, err := ProcessStackConfig(
atmosConfig,
stackBasePath,
terraformComponentsBasePath,
helmfileComponentsBasePath,
packerComponentsBasePath,
ansibleComponentsBasePath,
p,
deepMergedStackConfig,
processStackDeps,
processComponentDeps,
"",
componentStackMap,
importsConfig,
true)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
finalConfig["imports"] = uniqueImports
yamlConfig, err := u.ConvertToYAML(finalConfig)
if err != nil {
results <- stackProcessResult{index: i, err: err}
return
}
// Send result via channel (lock-free).
results <- stackProcessResult{
index: i,
stackFileName: stackFileName,
yamlConfig: yamlConfig,
finalConfig: finalConfig,
stackConfig: stackConfig,
importsConfig: importsConfig,
uniqueImports: uniqueImports,
mergeContext: mergeContext,
err: nil,
}
}(i, filePath)
}
// Close results channel when all goroutines complete.
go func() {
wg.Wait()
close(results)
}()
// Collect all results from channel (no lock contention).
for result := range results {
if result.err != nil {
return nil, nil, nil, result.err
}
// Store merge context for this stack file if provenance tracking is enabled.
if atmosConfig != nil && atmosConfig.TrackProvenance && result.mergeContext != nil && result.mergeContext.IsProvenanceEnabled() {
SetMergeContextForStack(result.stackFileName, result.mergeContext)
// Also set as last merge context for backward compatibility (note: may be overwritten by other results)
SetLastMergeContext(result.mergeContext)
}
listResult[result.index] = result.yamlConfig
mapResult[result.stackFileName] = result.finalConfig
rawStackConfigs[result.stackFileName] = map[string]any{
"stack": result.stackConfig,
"imports": result.importsConfig,
"import_files": result.uniqueImports,
}
}
return listResult, mapResult, rawStackConfigs, nil
}
// ProcessYAMLConfigFile takes a path to a YAML stack manifest,
// recursively processes and deep-merges all the imports,
// and returns the final stack config.
func ProcessYAMLConfigFile(
atmosConfig *schema.AtmosConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[string]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverridesInline map[string]any,
parentTerraformOverridesImports map[string]any,
parentHelmfileOverridesInline map[string]any,
parentHelmfileOverridesImports map[string]any,
atmosManifestJsonSchemaFilePath string,
) (
map[string]any,
map[string]map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
error,
) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFile")()
// Create merge context for single-file operations
var mergeContext *m.MergeContext
if atmosConfig != nil && atmosConfig.TrackProvenance {
mergeContext = m.NewMergeContext()
mergeContext.EnableProvenance()
}
// Call the context-aware version
deepMerged, imports, stackConfig, terraformInline, terraformImports, helmfileInline, helmfileImports, mergeContext, err := ProcessYAMLConfigFileWithContext(
atmosConfig,
basePath,
filePath,
importsConfig,
context,
ignoreMissingFiles,
skipTemplatesProcessingInImports,
ignoreMissingTemplateValues,
skipIfMissing,
parentTerraformOverridesInline,
parentTerraformOverridesImports,
parentHelmfileOverridesInline,
parentHelmfileOverridesImports,
atmosManifestJsonSchemaFilePath,
mergeContext,
)
// Store merge context if provenance tracking is enabled (for single-file operations like describe component)
if atmosConfig != nil && atmosConfig.TrackProvenance && mergeContext != nil && mergeContext.IsProvenanceEnabled() {
SetLastMergeContext(mergeContext)
}
return deepMerged, imports, stackConfig, terraformInline, terraformImports, helmfileInline, helmfileImports, err
}
// ProcessYAMLConfigFileWithContext takes a path to a YAML stack manifest,
// recursively processes and deep-merges all the imports with context tracking,
// and returns the final stack config.
func ProcessYAMLConfigFileWithContext(
atmosConfig *schema.AtmosConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[string]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverridesInline map[string]any,
parentTerraformOverridesImports map[string]any,
parentHelmfileOverridesInline map[string]any,
parentHelmfileOverridesImports map[string]any,
atmosManifestJsonSchemaFilePath string,
mergeContext *m.MergeContext,
) (
map[string]any,
map[string]map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
*m.MergeContext,
error,
) {
defer perf.Track(atmosConfig, "exec.ProcessYAMLConfigFileWithContext")()
return processYAMLConfigFileWithContextInternal(
atmosConfig,
basePath,
filePath,
importsConfig,
context,
ignoreMissingFiles,
skipTemplatesProcessingInImports,
ignoreMissingTemplateValues,
skipIfMissing,
parentTerraformOverridesInline,
parentTerraformOverridesImports,
parentHelmfileOverridesInline,
parentHelmfileOverridesImports,
atmosManifestJsonSchemaFilePath,
mergeContext,
)
}
// importFileResult holds the result of processing a single import file in parallel.
type importFileResult struct {
index int
importFile string
yamlConfig map[string]any
yamlConfigRaw map[string]any
terraformOverridesInline map[string]any
terraformOverridesImports map[string]any
helmfileOverridesInline map[string]any
helmfileOverridesImports map[string]any
importRelativePathWithoutExt string
mergeContext *m.MergeContext
err error
}
// processYAMLConfigFileWithContextInternal is the internal recursive implementation.
//
//nolint:gocognit,revive,cyclop,funlen
func processYAMLConfigFileWithContextInternal(
atmosConfig *schema.AtmosConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[string]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverridesInline map[string]any,
parentTerraformOverridesImports map[string]any,
parentHelmfileOverridesInline map[string]any,
parentHelmfileOverridesImports map[string]any,
atmosManifestJsonSchemaFilePath string,
mergeContext *m.MergeContext,
) (
map[string]any,
map[string]map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
map[string]any,
*m.MergeContext,
error,
) {
var stackConfigs []map[string]any
relativeFilePath := u.TrimBasePathFromPath(basePath+"/", filePath)
log.Trace("Processing YAML config file", "file", relativeFilePath)
// Initialize or update merge context with current file.
if mergeContext == nil {
mergeContext = m.NewMergeContext()
// Enable provenance if configured.
if atmosConfig != nil && atmosConfig.TrackProvenance {
mergeContext.EnableProvenance()
}
}
mergeContext = mergeContext.WithFile(relativeFilePath)
log.Trace("Merge context updated with file", "file", relativeFilePath, "import_chain_length", len(mergeContext.ImportChain), "track_provenance", atmosConfig != nil && atmosConfig.TrackProvenance)
globalTerraformSection := map[string]any{}
globalHelmfileSection := map[string]any{}
globalOverrides := map[string]any{}
terraformOverrides := map[string]any{}
helmfileOverrides := map[string]any{}
finalTerraformOverrides := map[string]any{}
finalHelmfileOverrides := map[string]any{}
// Use uncached file reads when provenance tracking is enabled to ensure YAML position tracking works correctly.
var stackYamlConfig string
var err error
if atmosConfig != nil && atmosConfig.TrackProvenance {
stackYamlConfig, err = GetFileContentWithoutCache(filePath)
} else {
stackYamlConfig, err = GetFileContent(filePath)
}
// If the file does not exist (`err != nil`), and `ignoreMissingFiles = true`, don't return the error.
//
// `ignoreMissingFiles = true` is used when executing `atmos describe affected` command.
// If we add a new stack manifest with some component configurations to the current branch, then the new file will not be present in
// the remote branch (with which the current branch is compared), and Atmos would throw an error.
//
// `skipIfMissing` is used in Atmos imports (https://atmos.tools/core-concepts/stacks/imports).
// Set it to `true` to ignore the imported manifest if it does not exist, and don't throw an error.
// This is useful when generating Atmos manifests using other tools, but the imported files are not present yet at the generation time.
if err != nil {
if ignoreMissingFiles || skipIfMissing {
return map[string]any{}, map[string]map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, nil, nil
} else {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
}
if stackYamlConfig == "" {
return map[string]any{}, map[string]map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, map[string]any{}, nil, nil
}
// Track whether context was originally provided from outside (e.g., via import context).
// This is important because we should only process templates during import when:
// 1. The file has a .tmpl extension, OR
// 2. Context was explicitly passed from outside (not just extracted from the file itself).
// Without this check, files with locals/settings/vars/env sections would have their templates
// processed prematurely, before component-specific context (like atmos_component) is available.
originalContextProvided := len(context) > 0
// Extract and resolve file-scoped locals before template processing.
// Locals can reference other locals using {{ .locals.X }} syntax.
// The resolved locals are added to the template context so they're available during template processing.
// This enables patterns like:
// locals:
// stage: prod
// name_prefix: "{{ .locals.stage }}-app"
// components:
// terraform:
// myapp:
// vars:
// name: "{{ .locals.name_prefix }}"
if !skipTemplatesProcessingInImports {
var localsErr error
context, localsErr = extractAndAddLocalsToContext(atmosConfig, stackYamlConfig, filePath, relativeFilePath, context)
if localsErr != nil {
if mergeContext != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, mergeContext.FormatError(localsErr, fmt.Sprintf("stack manifest '%s'", relativeFilePath))
}
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("stack manifest '%s': %w", relativeFilePath, localsErr)
}
}
stackManifestTemplatesProcessed := stackYamlConfig
stackManifestTemplatesErrorMessage := ""
// Process `Go` templates in the imported stack manifest if it has a template extension.
// Files with .yaml.tmpl or .yml.tmpl extensions are always processed as templates.
// Other .tmpl files are processed only when context is provided (backward compatibility).
// https://atmos.tools/core-concepts/stacks/imports#go-templates-in-imports
if !skipTemplatesProcessingInImports && (u.IsTemplateFile(filePath) || len(context) > 0) { //nolint:nestif // Template processing error handling requires conditional formatting based on context
var tmplErr error
stackManifestTemplatesProcessed, tmplErr = ProcessTmpl(atmosConfig, relativeFilePath, stackYamlConfig, context, ignoreMissingTemplateValues)
if tmplErr != nil {
// If template processing failed and the only context is from file extraction
// (locals/settings/vars/env, not from an explicit import context), this is likely
// due to templates referencing component context (like {{ .atmos_component }}) that
// isn't available during import. Fall back to the raw content — these templates will
// be processed later in ProcessStacks when the full component context is available.
if !originalContextProvided {
log.Debug("Template processing deferred for file with file-extracted context only",
"file", relativeFilePath, "error", tmplErr)
stackManifestTemplatesProcessed = stackYamlConfig
} else {
if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug {
stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig)
}
wrappedErr := fmt.Errorf("%w: %w", errUtils.ErrInvalidStackManifest, tmplErr)
if mergeContext != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, mergeContext.FormatError(wrappedErr, fmt.Sprintf("stack manifest '%s'%s", relativeFilePath, stackManifestTemplatesErrorMessage))
}
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w: stack manifest '%s'\n%w%s", errUtils.ErrInvalidStackManifest, relativeFilePath, tmplErr, stackManifestTemplatesErrorMessage)
}
}
}
stackConfigMap, positions, err := u.UnmarshalYAMLFromFileWithPositions[schema.AtmosSectionMapType](atmosConfig, stackManifestTemplatesProcessed, filePath)
if err != nil {
if atmosConfig.Logs.Level == u.LogLevelTrace || atmosConfig.Logs.Level == u.LogLevelDebug {
stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig)
}
// Check if we have merge context to provide enhanced error formatting
if mergeContext != nil {
// Wrap the error with the sentinel first to preserve it
wrappedErr := fmt.Errorf("%w: %v", errUtils.ErrInvalidStackManifest, err)
// Then format it with context information
e := mergeContext.FormatError(wrappedErr, fmt.Sprintf("stack manifest '%s'%s", relativeFilePath, stackManifestTemplatesErrorMessage))
return nil, nil, nil, nil, nil, nil, nil, nil, e
} else {
e := fmt.Errorf("%w: stack manifest '%s'\n%v%s", errUtils.ErrInvalidStackManifest, relativeFilePath, err, stackManifestTemplatesErrorMessage)
return nil, nil, nil, nil, nil, nil, nil, nil, e
}
}
// Store resolved file-level sections in stackConfigMap so they're available during describe_stacks.
// The context contains resolved values from extractAndAddLocalsToContext, but the YAML content
// (and thus stackConfigMap) may still have unresolved template expressions.
// By updating stackConfigMap with resolved values, we ensure templates like {{ .locals.X }}
// and {{ .vars.X }} can be resolved correctly.
if resolvedLocals, ok := context[cfg.LocalsSectionName].(map[string]any); ok && len(resolvedLocals) > 0 {
stackConfigMap[cfg.LocalsSectionName] = resolvedLocals
}
if resolvedVars, ok := context[cfg.VarsSectionName].(map[string]any); ok && len(resolvedVars) > 0 {
stackConfigMap[cfg.VarsSectionName] = resolvedVars
}
if resolvedSettings, ok := context[cfg.SettingsSectionName].(map[string]any); ok && len(resolvedSettings) > 0 {
stackConfigMap[cfg.SettingsSectionName] = resolvedSettings
}
if resolvedEnv, ok := context[cfg.EnvSectionName].(map[string]any); ok && len(resolvedEnv) > 0 {
stackConfigMap[cfg.EnvSectionName] = resolvedEnv
}
// Enable provenance tracking in merge context if tracking is enabled
if atmosConfig.TrackProvenance && mergeContext != nil && len(positions) > 0 {
mergeContext.EnableProvenance()
mergeContext.Positions = positions // Store positions for merge operations
}
// If the path to the Atmos manifest JSON Schema is provided, validate the stack manifest against it
if atmosManifestJsonSchemaFilePath != "" {
// Convert the data to JSON and back to Go map to prevent the error:
// jsonschema: invalid jsonType: map[interface {}]interface {}
dataJson, err := u.ConvertToJSONFast(stackConfigMap)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
dataFromJson, err := u.ConvertFromJSON(dataJson)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
atmosManifestJsonSchemaValidationErrorFormat := "Atmos manifest JSON Schema validation error in the file '%s':\n%v"
// Check cache first to avoid re-compiling the same schema for every stack file.
compiledSchema, found := getCachedCompiledSchema(atmosManifestJsonSchemaFilePath)
if !found {
// Schema not in cache - compile it and cache the result.
compiler := jsonschema.NewCompiler()
atmosManifestJsonSchemaFileReader, err := os.Open(atmosManifestJsonSchemaFilePath)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
defer func() {
_ = atmosManifestJsonSchemaFileReader.Close()
}()
if err := compiler.AddResource(atmosManifestJsonSchemaFilePath, atmosManifestJsonSchemaFileReader); err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
compiler.Draft = jsonschema.Draft2020
compiledSchema, err = compiler.Compile(atmosManifestJsonSchemaFilePath)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
// Store compiled schema in cache for reuse.
cacheCompiledSchema(atmosManifestJsonSchemaFilePath, compiledSchema)
}
// Validate using the compiled schema (whether cached or newly compiled).
if err = compiledSchema.Validate(dataFromJson); err != nil {
switch e := err.(type) {
case *jsonschema.ValidationError:
b, err2 := json.MarshalIndent(e.BasicOutput(), "", " ")
if err2 != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err2)
}
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, string(b))
default:
return nil, nil, nil, nil, nil, nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
}
}
// Check if the `overrides` sections exist and if we need to process overrides for the components in this stack manifest and its imports
// Global overrides in this stack manifest
if i, ok := stackConfigMap[cfg.OverridesSectionName]; ok {
if globalOverrides, ok = i.(map[string]any); !ok {
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w in the stack manifest '%s'", errUtils.ErrInvalidOverridesSection, relativeFilePath)
}
}
// Terraform overrides in this stack manifest
if o, ok := stackConfigMap[cfg.TerraformSectionName]; ok {
if globalTerraformSection, ok = o.(map[string]any); !ok {
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w in the stack manifest '%s'", errUtils.ErrInvalidTerraformSection, relativeFilePath)
}
if i, ok := globalTerraformSection[cfg.OverridesSectionName]; ok {
if terraformOverrides, ok = i.(map[string]any); !ok {
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w in the stack manifest '%s'", errUtils.ErrInvalidTerraformOverridesSection, relativeFilePath)
}
}
}
// Helmfile overrides in this stack manifest
if o, ok := stackConfigMap[cfg.HelmfileSectionName]; ok {
if globalHelmfileSection, ok = o.(map[string]any); !ok {
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w in the stack manifest '%s'", errUtils.ErrInvalidHelmfileSection, relativeFilePath)
}
if i, ok := globalHelmfileSection[cfg.OverridesSectionName]; ok {
if helmfileOverrides, ok = i.(map[string]any); !ok {
return nil, nil, nil, nil, nil, nil, nil, nil, fmt.Errorf("%w in the stack manifest '%s'", errUtils.ErrInvalidHelmfileOverridesSection, relativeFilePath)
}
}
}
parentTerraformOverridesInline, err = m.MergeWithContext(
atmosConfig,
[]map[string]any{globalOverrides, terraformOverrides, parentTerraformOverridesInline},
mergeContext,
)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
parentHelmfileOverridesInline, err = m.MergeWithContext(
atmosConfig,
[]map[string]any{globalOverrides, helmfileOverrides, parentHelmfileOverridesInline},
mergeContext,
)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
// Find and process all imports
importStructs, err := ProcessImportSection(stackConfigMap, relativeFilePath)
if err != nil {
return nil, nil, nil, nil, nil, nil, nil, nil, err
}
// Record provenance for each import if provenance tracking is enabled.