/
stack_processor.go
1447 lines (1261 loc) 路 50.6 KB
/
stack_processor.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
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 stack
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/santhosh-tekuri/jsonschema/v5"
"gopkg.in/yaml.v2"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
cfg "github.com/cloudposse/atmos/pkg/config"
c "github.com/cloudposse/atmos/pkg/convert"
m "github.com/cloudposse/atmos/pkg/merge"
"github.com/cloudposse/atmos/pkg/schema"
u "github.com/cloudposse/atmos/pkg/utils"
)
var (
// Mutex to serialize updates of the result map of ProcessYAMLConfigFiles function
processYAMLConfigFilesLock = &sync.Mutex{}
)
// ProcessYAMLConfigFiles takes a list of paths to stack manifests, processes and deep-merges all imports,
// and returns a list of stack configs
func ProcessYAMLConfigFiles(
cliConfig schema.CliConfiguration,
stacksBasePath string,
terraformComponentsBasePath string,
helmfileComponentsBasePath string,
filePaths []string,
processStackDeps bool,
processComponentDeps bool,
ignoreMissingFiles bool,
) (
[]string,
map[string]any,
map[string]map[string]any,
error,
) {
count := len(filePaths)
listResult := make([]string, count)
mapResult := map[string]any{}
rawStackConfigs := map[string]map[string]any{}
var errorResult error
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 = path.Dir(p)
}
stackFileName := strings.TrimSuffix(
strings.TrimSuffix(
u.TrimBasePathFromPath(stackBasePath+"/", p),
cfg.DefaultStackConfigFileExtension),
".yml",
)
deepMergedStackConfig, importsConfig, stackConfig, err := ProcessYAMLConfigFile(
cliConfig,
stackBasePath,
p,
map[string]map[any]any{},
nil,
ignoreMissingFiles,
false,
false,
false,
map[any]any{},
map[any]any{},
"",
)
if err != nil {
errorResult = err
return
}
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(
stackBasePath,
terraformComponentsBasePath,
helmfileComponentsBasePath,
p,
deepMergedStackConfig,
processStackDeps,
processComponentDeps,
"",
componentStackMap,
importsConfig,
true)
if err != nil {
errorResult = err
return
}
finalConfig["imports"] = uniqueImports
yamlConfig, err := yaml.Marshal(finalConfig)
if err != nil {
errorResult = err
return
}
processYAMLConfigFilesLock.Lock()
defer processYAMLConfigFilesLock.Unlock()
listResult[i] = string(yamlConfig)
mapResult[stackFileName] = finalConfig
rawStackConfigs[stackFileName] = map[string]any{}
rawStackConfigs[stackFileName]["stack"] = stackConfig
rawStackConfigs[stackFileName]["imports"] = importsConfig
rawStackConfigs[stackFileName]["import_files"] = uniqueImports
}(i, filePath)
}
wg.Wait()
if errorResult != nil {
return nil, nil, nil, errorResult
}
return listResult, mapResult, rawStackConfigs, nil
}
// ProcessYAMLConfigFile takes a path to a YAML stack manifest,
// recursively processes and deep-merges all imports,
// and returns the final stack config
func ProcessYAMLConfigFile(
cliConfig schema.CliConfiguration,
basePath string,
filePath string,
importsConfig map[string]map[any]any,
context map[string]any,
ignoreMissingFiles bool,
skipTemplatesProcessingInImports bool,
ignoreMissingTemplateValues bool,
skipIfMissing bool,
parentTerraformOverrides map[any]any,
parentHelmfileOverrides map[any]any,
atmosManifestJsonSchemaFilePath string,
) (
map[any]any,
map[string]map[any]any,
map[any]any,
error,
) {
var stackConfigs []map[any]any
relativeFilePath := u.TrimBasePathFromPath(basePath+"/", filePath)
globalTerraformSection := map[any]any{}
globalHelmfileSection := map[any]any{}
globalOverrides := map[any]any{}
terraformOverrides := map[any]any{}
helmfileOverrides := map[any]any{}
finalTerraformOverrides := map[any]any{}
finalHelmfileOverrides := map[any]any{}
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[any]any{}, map[string]map[any]any{}, map[any]any{}, nil
} else {
return nil, nil, nil, err
}
}
stackManifestTemplatesProcessed := stackYamlConfig
stackManifestTemplatesErrorMessage := ""
// Process `Go` templates in the imported stack manifest using the provided `context`
// https://atmos.tools/core-concepts/stacks/imports#go-templates-in-imports
if !skipTemplatesProcessingInImports && len(context) > 0 {
stackManifestTemplatesProcessed, err = u.ProcessTmpl(relativeFilePath, stackYamlConfig, context, ignoreMissingTemplateValues)
if err != nil {
if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug {
stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig)
}
e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)
return nil, nil, nil, e
}
}
stackConfigMap, err := c.YAMLToMapOfInterfaces(stackManifestTemplatesProcessed)
if err != nil {
if cliConfig.Logs.Level == u.LogLevelTrace || cliConfig.Logs.Level == u.LogLevelDebug {
stackManifestTemplatesErrorMessage = fmt.Sprintf("\n\n%s", stackYamlConfig)
}
e := fmt.Errorf("invalid stack manifest '%s'\n%v%s", relativeFilePath, err, stackManifestTemplatesErrorMessage)
return nil, nil, nil, e
}
// 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, err
}
dataFromJson, err := u.ConvertFromJSON(dataJson)
if err != nil {
return nil, nil, nil, err
}
compiler := jsonschema.NewCompiler()
atmosManifestJsonSchemaValidationErrorFormat := "Atmos manifest JSON Schema validation error in the file '%s':\n%v"
atmosManifestJsonSchemaFileReader, err := os.Open(atmosManifestJsonSchemaFilePath)
if err != nil {
return nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
if err := compiler.AddResource(atmosManifestJsonSchemaFilePath, atmosManifestJsonSchemaFileReader); err != nil {
return nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
compiler.Draft = jsonschema.Draft2020
compiledSchema, err := compiler.Compile(atmosManifestJsonSchemaFilePath)
if err != nil {
return nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err)
}
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, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, err2)
}
return nil, nil, nil, errors.Errorf(atmosManifestJsonSchemaValidationErrorFormat, relativeFilePath, string(b))
default:
return 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
if i, ok := stackConfigMap[cfg.OverridesSectionName]; ok {
if globalOverrides, ok = i.(map[any]any); !ok {
return nil, nil, nil, fmt.Errorf("invalid 'overrides' section in the stack manifest '%s'", relativeFilePath)
}
}
// Terraform overrides
if o, ok := stackConfigMap["terraform"]; ok {
if globalTerraformSection, ok = o.(map[any]any); !ok {
return nil, nil, nil, fmt.Errorf("invalid 'terraform' section in the stack manifest '%s'", relativeFilePath)
}
if i, ok := globalTerraformSection[cfg.OverridesSectionName]; ok {
if terraformOverrides, ok = i.(map[any]any); !ok {
return nil, nil, nil, fmt.Errorf("invalid 'terraform.overrides' section in the stack manifest '%s'", relativeFilePath)
}
}
}
finalTerraformOverrides, err = m.Merge([]map[any]any{globalOverrides, terraformOverrides, parentTerraformOverrides})
if err != nil {
return nil, nil, nil, err
}
// Helmfile overrides
if o, ok := stackConfigMap["helmfile"]; ok {
if globalHelmfileSection, ok = o.(map[any]any); !ok {
return nil, nil, nil, fmt.Errorf("invalid 'helmfile' section in the stack manifest '%s'", relativeFilePath)
}
if i, ok := globalHelmfileSection[cfg.OverridesSectionName]; ok {
if helmfileOverrides, ok = i.(map[any]any); !ok {
return nil, nil, nil, fmt.Errorf("invalid 'terraform.overrides' section in the stack manifest '%s'", relativeFilePath)
}
}
}
finalHelmfileOverrides, err = m.Merge([]map[any]any{globalOverrides, helmfileOverrides, parentHelmfileOverrides})
if err != nil {
return nil, nil, nil, err
}
// Add the `overrides` section for all components in this manifest
if len(finalTerraformOverrides) > 0 || len(finalHelmfileOverrides) > 0 {
if componentsSection, ok := stackConfigMap["components"].(map[any]any); ok {
// Terraform
if len(finalTerraformOverrides) > 0 {
if terraformSection, ok := componentsSection["terraform"].(map[any]any); ok {
for _, compSection := range terraformSection {
if componentSection, ok := compSection.(map[any]any); ok {
componentSection["overrides"] = finalTerraformOverrides
}
}
}
}
// Helmfile
if len(finalHelmfileOverrides) > 0 {
if helmfileSection, ok := componentsSection["helmfile"].(map[any]any); ok {
for _, compSection := range helmfileSection {
if componentSection, ok := compSection.(map[any]any); ok {
componentSection["overrides"] = finalHelmfileOverrides
}
}
}
}
}
}
// Find and process all imports
importStructs, err := processImportSection(stackConfigMap, relativeFilePath)
if err != nil {
return nil, nil, nil, err
}
for _, importStruct := range importStructs {
imp := importStruct.Path
if imp == "" {
return nil, nil, nil, fmt.Errorf("invalid empty import in the manifest '%s'", relativeFilePath)
}
// If the import file is specified without extension, use `.yaml` as default
impWithExt := imp
ext := filepath.Ext(imp)
if ext == "" {
ext = cfg.DefaultStackConfigFileExtension
impWithExt = imp + ext
}
impWithExtPath := path.Join(basePath, impWithExt)
if impWithExtPath == filePath {
errorMessage := fmt.Sprintf("invalid import in the manifest '%s'\nThe file imports itself in '%s'",
relativeFilePath,
imp)
return nil, nil, nil, errors.New(errorMessage)
}
// Find all import matches in the glob
importMatches, err := u.GetGlobMatches(impWithExtPath)
if err != nil || len(importMatches) == 0 {
// Retry (b/c we are using `doublestar` library and it sometimes has issues reading many files in a Docker container)
// TODO: review `doublestar` library
importMatches, err = u.GetGlobMatches(impWithExtPath)
if err != nil || len(importMatches) == 0 {
// The import was not found -> check if the import is a Go template; if not, return the error
isGolangTemplate, err2 := u.IsGolangTemplate(imp)
if err2 != nil {
return nil, nil, nil, err2
}
// If the import is not a Go template and SkipIfMissing is false, return the error
if !isGolangTemplate && !importStruct.SkipIfMissing {
if err != nil {
errorMessage := fmt.Sprintf("no matches found for the import '%s' in the file '%s'\nError: %s",
imp,
relativeFilePath,
err,
)
return nil, nil, nil, errors.New(errorMessage)
} else if importMatches == nil {
errorMessage := fmt.Sprintf("no matches found for the import '%s' in the file '%s'",
imp,
relativeFilePath,
)
return nil, nil, nil, errors.New(errorMessage)
}
}
}
}
// Support `context` in hierarchical imports.
// Deep-merge the parent `context` with the current `context` and propagate the result to the entire chain of imports.
// The parent `context` takes precedence over the current (imported) `context` and will override items with the same keys.
// TODO: instead of calling the conversion functions, we need to switch to generics and update everything to support it
listOfMaps := []map[any]any{c.MapsOfStringsToMapsOfInterfaces(importStruct.Context), c.MapsOfStringsToMapsOfInterfaces(context)}
mergedContext, err := m.Merge(listOfMaps)
if err != nil {
return nil, nil, nil, err
}
// Process the imports in the current manifest
for _, importFile := range importMatches {
yamlConfig, _, yamlConfigRaw, err := ProcessYAMLConfigFile(
cliConfig,
basePath,
importFile,
importsConfig,
c.MapsOfInterfacesToMapsOfStrings(mergedContext),
ignoreMissingFiles,
importStruct.SkipTemplatesProcessing,
true, // importStruct.IgnoreMissingTemplateValues,
importStruct.SkipIfMissing,
finalTerraformOverrides,
finalHelmfileOverrides,
"",
)
if err != nil {
return nil, nil, nil, err
}
stackConfigs = append(stackConfigs, yamlConfig)
importRelativePathWithExt := strings.Replace(importFile, basePath+"/", "", 1)
ext2 := filepath.Ext(importRelativePathWithExt)
if ext2 == "" {
ext2 = cfg.DefaultStackConfigFileExtension
}
importRelativePathWithoutExt := strings.TrimSuffix(importRelativePathWithExt, ext2)
importsConfig[importRelativePathWithoutExt] = yamlConfigRaw
}
}
if len(stackConfigMap) > 0 {
stackConfigs = append(stackConfigs, stackConfigMap)
}
// Deep-merge the stack manifest and all the imports
stackConfigsDeepMerged, err := m.Merge(stackConfigs)
if err != nil {
return nil, nil, nil, err
}
return stackConfigsDeepMerged, importsConfig, stackConfigMap, nil
}
// ProcessStackConfig takes a stack manifest, deep-merges all variables, settings, environments and backends,
// and returns the final stack configuration for all Terraform and helmfile components
func ProcessStackConfig(
stacksBasePath string,
terraformComponentsBasePath string,
helmfileComponentsBasePath string,
stack string,
config map[any]any,
processStackDeps bool,
processComponentDeps bool,
componentTypeFilter string,
componentStackMap map[string]map[string][]string,
importsConfig map[string]map[any]any,
checkBaseComponentExists bool,
) (map[any]any, error) {
stackName := strings.TrimSuffix(
strings.TrimSuffix(
u.TrimBasePathFromPath(stacksBasePath+"/", stack),
cfg.DefaultStackConfigFileExtension),
".yml",
)
globalVarsSection := map[any]any{}
globalSettingsSection := map[any]any{}
globalEnvSection := map[any]any{}
globalTerraformSection := map[any]any{}
globalHelmfileSection := map[any]any{}
globalComponentsSection := map[any]any{}
terraformVars := map[any]any{}
terraformSettings := map[any]any{}
terraformEnv := map[any]any{}
terraformCommand := ""
terraformProviders := map[any]any{}
helmfileVars := map[any]any{}
helmfileSettings := map[any]any{}
helmfileEnv := map[any]any{}
helmfileCommand := ""
terraformComponents := map[string]any{}
helmfileComponents := map[string]any{}
allComponents := map[string]any{}
// Global sections
if i, ok := config["vars"]; ok {
globalVarsSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'vars' section in the file '%s'", stackName)
}
}
if i, ok := config["settings"]; ok {
globalSettingsSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'settings' section in the file '%s'", stackName)
}
}
if i, ok := config["env"]; ok {
globalEnvSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'env' section in the file '%s'", stackName)
}
}
if i, ok := config["terraform"]; ok {
globalTerraformSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform' section in the file '%s'", stackName)
}
}
if i, ok := config["helmfile"]; ok {
globalHelmfileSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'helmfile' section in the file '%s'", stackName)
}
}
if i, ok := config["components"]; ok {
globalComponentsSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components' section in the file '%s'", stackName)
}
}
// Terraform section
if i, ok := globalTerraformSection["command"]; ok {
terraformCommand, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.command' section in the file '%s'", stackName)
}
}
if i, ok := globalTerraformSection["vars"]; ok {
terraformVars, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.vars' section in the file '%s'", stackName)
}
}
globalAndTerraformVars, err := m.Merge([]map[any]any{globalVarsSection, terraformVars})
if err != nil {
return nil, err
}
if i, ok := globalTerraformSection["settings"]; ok {
terraformSettings, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.settings' section in the file '%s'", stackName)
}
}
globalAndTerraformSettings, err := m.Merge([]map[any]any{globalSettingsSection, terraformSettings})
if err != nil {
return nil, err
}
if i, ok := globalTerraformSection["env"]; ok {
terraformEnv, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.env' section in the file '%s'", stackName)
}
}
globalAndTerraformEnv, err := m.Merge([]map[any]any{globalEnvSection, terraformEnv})
if err != nil {
return nil, err
}
if i, ok := globalTerraformSection[cfg.ProvidersSectionName]; ok {
terraformProviders, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.providers' section in the file '%s'", stackName)
}
}
// Global backend
globalBackendType := ""
globalBackendSection := map[any]any{}
if i, ok := globalTerraformSection["backend_type"]; ok {
globalBackendType, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.backend_type' section in the file '%s'", stackName)
}
}
if i, ok := globalTerraformSection["backend"]; ok {
globalBackendSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.backend' section in the file '%s'", stackName)
}
}
// Global remote state backend
globalRemoteStateBackendType := ""
globalRemoteStateBackendSection := map[any]any{}
if i, ok := globalTerraformSection["remote_state_backend_type"]; ok {
globalRemoteStateBackendType, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.remote_state_backend_type' section in the file '%s'", stackName)
}
}
if i, ok := globalTerraformSection["remote_state_backend"]; ok {
globalRemoteStateBackendSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'terraform.remote_state_backend' section in the file '%s'", stackName)
}
}
// Helmfile section
if i, ok := globalHelmfileSection["command"]; ok {
helmfileCommand, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'helmfile.command' section in the file '%s'", stackName)
}
}
if i, ok := globalHelmfileSection["vars"]; ok {
helmfileVars, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'helmfile.vars' section in the file '%s'", stackName)
}
}
globalAndHelmfileVars, err := m.Merge([]map[any]any{globalVarsSection, helmfileVars})
if err != nil {
return nil, err
}
if i, ok := globalHelmfileSection["settings"]; ok {
helmfileSettings, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'helmfile.settings' section in the file '%s'", stackName)
}
}
globalAndHelmfileSettings, err := m.Merge([]map[any]any{globalSettingsSection, helmfileSettings})
if err != nil {
return nil, err
}
if i, ok := globalHelmfileSection["env"]; ok {
helmfileEnv, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'helmfile.env' section in the file '%s'", stackName)
}
}
globalAndHelmfileEnv, err := m.Merge([]map[any]any{globalEnvSection, helmfileEnv})
if err != nil {
return nil, err
}
// Process all Terraform components
if componentTypeFilter == "" || componentTypeFilter == "terraform" {
if allTerraformComponents, ok := globalComponentsSection["terraform"]; ok {
allTerraformComponentsMap, ok := allTerraformComponents.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform' section in the file '%s'", stackName)
}
for cmp, v := range allTerraformComponentsMap {
component := cmp.(string)
componentMap, ok := v.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s' section in the file '%s'", component, stackName)
}
componentVars := map[any]any{}
if i, ok := componentMap[cfg.VarsSectionName]; ok {
componentVars, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.vars' section in the file '%s'", component, stackName)
}
}
componentSettings := map[any]any{}
if i, ok := componentMap[cfg.SettingsSectionName]; ok {
componentSettings, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.settings' section in the file '%s'", component, stackName)
}
if i, ok := componentSettings["spacelift"]; ok {
_, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.settings.spacelift' section in the file '%s'", component, stackName)
}
}
}
componentEnv := map[any]any{}
if i, ok := componentMap[cfg.EnvSectionName]; ok {
componentEnv, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.env' section in the file '%s'", component, stackName)
}
}
componentProviders := map[any]any{}
if i, ok := componentMap[cfg.ProvidersSectionName]; ok {
componentProviders, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.providers' section in the file '%s'", component, stackName)
}
}
// Component metadata.
// This is per component, not deep-merged and not inherited from base components and globals.
componentMetadata := map[any]any{}
if i, ok := componentMap[cfg.MetadataSectionName]; ok {
componentMetadata, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.metadata' section in the file '%s'", component, stackName)
}
}
// Component backend
componentBackendType := ""
componentBackendSection := map[any]any{}
if i, ok := componentMap[cfg.BackendTypeSectionName]; ok {
componentBackendType, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.backend_type' attribute in the file '%s'", component, stackName)
}
}
if i, ok := componentMap[cfg.BackendSectionName]; ok {
componentBackendSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.backend' section in the file '%s'", component, stackName)
}
}
// Component remote state backend
componentRemoteStateBackendType := ""
componentRemoteStateBackendSection := map[any]any{}
if i, ok := componentMap["remote_state_backend_type"]; ok {
componentRemoteStateBackendType, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.remote_state_backend_type' attribute in the file '%s'", component, stackName)
}
}
if i, ok := componentMap["remote_state_backend"]; ok {
componentRemoteStateBackendSection, ok = i.(map[any]any)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.remote_state_backend' section in the file '%s'", component, stackName)
}
}
componentTerraformCommand := ""
if i, ok := componentMap["command"]; ok {
componentTerraformCommand, ok = i.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.command' attribute in the file '%s'", component, stackName)
}
}
// Process overrides
componentOverrides := map[any]any{}
componentOverridesVars := map[any]any{}
componentOverridesSettings := map[any]any{}
componentOverridesEnv := map[any]any{}
componentOverridesProviders := map[any]any{}
componentOverridesTerraformCommand := ""
if i, ok := componentMap[cfg.OverridesSectionName]; ok {
if componentOverrides, ok = i.(map[any]any); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides' in the manifest '%s'", component, stackName)
}
if i, ok = componentOverrides[cfg.VarsSectionName]; ok {
if componentOverridesVars, ok = i.(map[any]any); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides.vars' in the manifest '%s'", component, stackName)
}
}
if i, ok = componentOverrides[cfg.SettingsSectionName]; ok {
if componentOverridesSettings, ok = i.(map[any]any); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides.settings' in the manifest '%s'", component, stackName)
}
}
if i, ok = componentOverrides[cfg.EnvSectionName]; ok {
if componentOverridesEnv, ok = i.(map[any]any); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides.env' in the manifest '%s'", component, stackName)
}
}
if i, ok = componentOverrides["command"]; ok {
if componentOverridesTerraformCommand, ok = i.(string); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides.command' in the manifest '%s'", component, stackName)
}
}
if i, ok = componentOverrides[cfg.ProvidersSectionName]; ok {
if componentOverridesProviders, ok = i.(map[any]any); !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.overrides.providers' in the manifest '%s'", component, stackName)
}
}
}
// Process base component(s)
baseComponentName := ""
baseComponentVars := map[any]any{}
baseComponentSettings := map[any]any{}
baseComponentEnv := map[any]any{}
baseComponentProviders := map[any]any{}
baseComponentTerraformCommand := ""
baseComponentBackendType := ""
baseComponentBackendSection := map[any]any{}
baseComponentRemoteStateBackendType := ""
baseComponentRemoteStateBackendSection := map[any]any{}
var baseComponentConfig schema.BaseComponentConfig
var componentInheritanceChain []string
var baseComponents []string
// Inheritance using the top-level `component` attribute
if baseComponent, baseComponentExist := componentMap["component"]; baseComponentExist {
baseComponentName, ok = baseComponent.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.component' attribute in the file '%s'", component, stackName)
}
// Process the base components recursively to find `componentInheritanceChain`
err = ProcessBaseComponentConfig(
&baseComponentConfig,
allTerraformComponentsMap,
component,
stack,
baseComponentName,
terraformComponentsBasePath,
checkBaseComponentExists,
&baseComponents,
)
if err != nil {
return nil, err
}
baseComponentVars = baseComponentConfig.BaseComponentVars
baseComponentSettings = baseComponentConfig.BaseComponentSettings
baseComponentEnv = baseComponentConfig.BaseComponentEnv
baseComponentProviders = baseComponentConfig.BaseComponentProviders
baseComponentName = baseComponentConfig.FinalBaseComponentName
baseComponentTerraformCommand = baseComponentConfig.BaseComponentCommand
baseComponentBackendType = baseComponentConfig.BaseComponentBackendType
baseComponentBackendSection = baseComponentConfig.BaseComponentBackendSection
baseComponentRemoteStateBackendType = baseComponentConfig.BaseComponentRemoteStateBackendType
baseComponentRemoteStateBackendSection = baseComponentConfig.BaseComponentRemoteStateBackendSection
componentInheritanceChain = baseComponentConfig.ComponentInheritanceChain
}
// Multiple inheritance (and multiple-inheritance chain) using `metadata.component` and `metadata.inherit`.
// `metadata.component` points to the component implementation (e.g. in `components/terraform` folder),
// it does not specify inheritance (it overrides the deprecated top-level `component` attribute).
// `metadata.inherit` is a list of component names from which the current component inherits.
// It uses a method similar to Method Resolution Order (MRO), which is how Python supports multiple inheritance.
//
// In the case of multiple base components, it is processed left to right, in the order by which it was declared.
// For example: `metadata.inherits: [componentA, componentB]`
// will deep-merge all the base components of `componentA` (each component overriding its base),
// then all the base components of `componentB` (each component overriding its base),
// then the two results are deep-merged together (`componentB` inheritance chain will override values from 'componentA' inheritance chain).
if baseComponentFromMetadata, baseComponentFromMetadataExist := componentMetadata["component"]; baseComponentFromMetadataExist {
baseComponentName, ok = baseComponentFromMetadata.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.metadata.component' attribute in the file '%s'", component, stackName)
}
}
baseComponents = append(baseComponents, baseComponentName)
if inheritList, inheritListExist := componentMetadata["inherits"].([]any); inheritListExist {
for _, v := range inheritList {
baseComponentFromInheritList, ok := v.(string)
if !ok {
return nil, fmt.Errorf("invalid 'components.terraform.%s.metadata.inherits' section in the file '%s'", component, stackName)
}
if _, ok := allTerraformComponentsMap[baseComponentFromInheritList]; !ok {
if checkBaseComponentExists {
errorMessage := fmt.Sprintf("The component '%[1]s' in the stack '%[2]s' inherits from '%[3]s' "+
"(using 'metadata.inherits'), but '%[3]s' is not defined in any of the config files for the stack '%[2]s'",
component,
stackName,
baseComponentFromInheritList,
)
return nil, errors.New(errorMessage)
}
}
// Process the baseComponentFromInheritList components recursively to find `componentInheritanceChain`
err = ProcessBaseComponentConfig(
&baseComponentConfig,
allTerraformComponentsMap,
component,
stack,
baseComponentFromInheritList,
terraformComponentsBasePath,
checkBaseComponentExists,
&baseComponents,
)
if err != nil {
return nil, err
}
baseComponentVars = baseComponentConfig.BaseComponentVars
baseComponentSettings = baseComponentConfig.BaseComponentSettings
baseComponentEnv = baseComponentConfig.BaseComponentEnv
baseComponentTerraformCommand = baseComponentConfig.BaseComponentCommand
baseComponentBackendType = baseComponentConfig.BaseComponentBackendType
baseComponentBackendSection = baseComponentConfig.BaseComponentBackendSection
baseComponentRemoteStateBackendType = baseComponentConfig.BaseComponentRemoteStateBackendType
baseComponentRemoteStateBackendSection = baseComponentConfig.BaseComponentRemoteStateBackendSection
componentInheritanceChain = baseComponentConfig.ComponentInheritanceChain
}
}
baseComponents = u.UniqueStrings(baseComponents)
sort.Strings(baseComponents)
// Final configs
finalComponentVars, err := m.Merge([]map[any]any{
globalAndTerraformVars,
baseComponentVars,
componentVars,
componentOverridesVars,
})
if err != nil {
return nil, err
}
finalComponentSettings, err := m.Merge([]map[any]any{
globalAndTerraformSettings,
baseComponentSettings,
componentSettings,
componentOverridesSettings,
})
if err != nil {
return nil, err
}
finalComponentEnv, err := m.Merge([]map[any]any{
globalAndTerraformEnv,
baseComponentEnv,
componentEnv,
componentOverridesEnv,
})
if err != nil {
return nil, err
}
finalComponentProviders, err := m.Merge([]map[any]any{
terraformProviders,
baseComponentProviders,
componentProviders,
componentOverridesProviders,
})
if err != nil {
return nil, err
}
// Final backend
finalComponentBackendType := globalBackendType
if len(baseComponentBackendType) > 0 {
finalComponentBackendType = baseComponentBackendType
}
if len(componentBackendType) > 0 {