-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathexpansion_test.go
More file actions
1338 lines (1099 loc) · 29.9 KB
/
Copy pathexpansion_test.go
File metadata and controls
1338 lines (1099 loc) · 29.9 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 config_test
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strconv"
"testing"
"github.com/gruntwork-io/terragrunt/internal/experiment"
"github.com/gruntwork-io/terragrunt/internal/vfs"
"github.com/gruntwork-io/terragrunt/pkg/config"
"github.com/gruntwork-io/terragrunt/pkg/config/hclparse"
"github.com/gruntwork-io/terragrunt/test/helpers"
"github.com/gruntwork-io/terragrunt/test/helpers/logger"
"github.com/gruntwork-io/terragrunt/test/helpers/venvtest"
"github.com/hashicorp/hcl/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zclconf/go-cty/cty"
)
const dependencyWithExpansionHCL = `
dependency "aurora" {
expansion {
for_each = toset(["web", "api"])
}
config_path = "../aurora"
}
`
const unitWithExpansionHCL = `
unit "app" {
expansion {
for_each = toset(["web", "api"])
}
source = "./modules/app"
path = "app/${each.key}"
}
`
const jsonConfigPath = "terragrunt.hcl.json"
const jsonDependencyWithExpansion = `
{"dependency": {"aurora": {"expansion": {"count": 2}, "config_path": "../aurora-${count.index}"}}}
`
const stackWithExpansionHCL = `
stack "team" {
expansion {
count = 2
}
source = "./stacks/team"
path = "team/${count.index}"
}
`
// TestValidateExpansionExperiment pins which blocks the gate rejects while the
// block-iteration experiment is off, and that it names the offending block.
func TestValidateExpansionExperiment(t *testing.T) {
t.Parallel()
skipInExperimentMode(t)
testCases := []struct {
name string
configPath string
cfg string
wantBlockType string
wantLabel string
wantErr bool
}{
{
name: "dependency with expansion",
configPath: config.DefaultTerragruntConfigPath,
cfg: dependencyWithExpansionHCL,
wantBlockType: "dependency",
wantLabel: "aurora",
wantErr: true,
},
{
name: "unit with expansion",
configPath: config.DefaultStackFile,
cfg: unitWithExpansionHCL,
wantBlockType: "unit",
wantLabel: "app",
wantErr: true,
},
{
name: "stack with expansion",
configPath: config.DefaultStackFile,
cfg: stackWithExpansionHCL,
wantBlockType: "stack",
wantLabel: "team",
wantErr: true,
},
{
name: "dependency without expansion",
configPath: config.DefaultTerragruntConfigPath,
cfg: `
dependency "vpc" {
config_path = "../vpc"
}
`,
},
{
name: "unit without expansion",
configPath: config.DefaultStackFile,
cfg: `
unit "app" {
source = "./modules/app"
path = "app"
}
`,
},
{
name: "expansion outside an expandable block",
configPath: config.DefaultTerragruntConfigPath,
cfg: `
generate "backend" {
expansion {
count = 2
}
path = "backend.tf"
if_exists = "overwrite"
contents = ""
}
`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
file := parseHCLString(t, tc.cfg, tc.configPath)
err := config.ValidateExpansionExperiment(experiment.NewExperiments(), file)
if !tc.wantErr {
require.NoError(t, err)
return
}
var typed config.ExpansionRequiresExperimentError
require.ErrorAs(t, err, &typed)
assert.Equal(t, tc.wantBlockType, typed.BlockType)
assert.Equal(t, tc.wantLabel, typed.BlockLabel)
assert.Equal(t, tc.configPath, typed.ConfigPath)
})
}
}
// TestValidateExpansionExperimentEnabled pins that enabling the experiment clears the
// gate for every block type it covers.
func TestValidateExpansionExperimentEnabled(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
configPath string
cfg string
}{
{
name: "dependency",
configPath: config.DefaultTerragruntConfigPath,
cfg: dependencyWithExpansionHCL,
},
{
name: "unit",
configPath: config.DefaultStackFile,
cfg: unitWithExpansionHCL,
},
{
name: "stack",
configPath: config.DefaultStackFile,
cfg: stackWithExpansionHCL,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
experiments := experiment.NewExperiments()
require.NoError(t, experiments.EnableExperiment(experiment.BlockIteration))
require.NoError(
t,
config.ValidateExpansionExperiment(
experiments,
parseHCLString(t, tc.cfg, tc.configPath),
),
)
})
}
}
// TestParseConfigStringExpansionRequiresExperiment proves the gate is wired into the
// unit config parse, not just callable on its own.
func TestParseConfigStringExpansionRequiresExperiment(t *testing.T) {
t.Parallel()
skipInExperimentMode(t)
l := logger.CreateLogger()
ctx, pctx := newTestParsingContext(t, venvtest.NewOSWithEmptyEnv(), config.DefaultTerragruntConfigPath)
_, err := config.ParseConfigString(
ctx,
pctx,
l,
config.DefaultTerragruntConfigPath,
dependencyWithExpansionHCL,
nil,
)
var typed config.ExpansionRequiresExperimentError
require.ErrorAs(t, err, &typed)
assert.Equal(t, "dependency", typed.BlockType)
}
// TestReadStackConfigStringExpansionRequiresExperiment proves the gate is wired into the
// stack parse. A unit block decodes through an `hcl:",remain"` field that would otherwise
// absorb the expansion block without complaint.
func TestReadStackConfigStringExpansionRequiresExperiment(t *testing.T) {
t.Parallel()
skipInExperimentMode(t)
testCases := []struct {
name string
cfg string
wantBlockType string
}{
{
name: "unit",
cfg: unitWithExpansionHCL,
wantBlockType: "unit",
},
{
name: "stack",
cfg: stackWithExpansionHCL,
wantBlockType: "stack",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
l := logger.CreateLogger()
ctx, pctx := newTestParsingContext(t, venvtest.NewOSWithEmptyEnv(), config.DefaultStackFile)
_, err := config.ReadStackConfigString(
ctx,
l,
pctx,
config.DefaultStackFile,
tc.cfg,
nil,
)
var typed config.ExpansionRequiresExperimentError
require.ErrorAs(t, err, &typed)
assert.Equal(t, tc.wantBlockType, typed.BlockType)
})
}
}
// TestReadStackConfigFileExpansionInIncludeRequiresExperiment pins that the gate follows
// include blocks. Included stack files decode straight to StackConfigFile without going
// back through ParseStackConfig, so they are gated separately.
func TestReadStackConfigFileExpansionInIncludeRequiresExperiment(t *testing.T) {
t.Parallel()
skipInExperimentMode(t)
const dir = "/stack"
fsys := vfs.NewMemMapFS()
require.NoError(t, vfs.WriteFile(
fsys,
filepath.Join(dir, "included.stack.hcl"),
[]byte(unitWithExpansionHCL),
0o644,
))
stackPath := filepath.Join(dir, config.DefaultStackFile)
require.NoError(t, vfs.WriteFile(fsys, stackPath, []byte(`
include "extra" {
path = "included.stack.hcl"
}
`), 0o644))
l := logger.CreateLogger()
ctx, pctx := newTestParsingContext(t, venvtest.NewOSWithEmptyEnv(), stackPath)
pctx.Venv.FS = fsys
_, err := config.ReadStackConfigFile(ctx, l, pctx, stackPath, nil)
var typed config.ExpansionRequiresExperimentError
require.ErrorAs(t, err, &typed)
assert.Equal(t, "unit", typed.BlockType)
}
// TestExpansionRequiresExperimentErrorNamesTheFlag pins that the error a user reads
// names the experiment they need, with and without a block label.
func TestExpansionRequiresExperimentErrorNamesTheFlag(t *testing.T) {
t.Parallel()
labeled := config.ExpansionRequiresExperimentError{
ConfigPath: config.DefaultTerragruntConfigPath,
BlockType: "dependency",
BlockLabel: "aurora",
}
assert.Contains(t, labeled.Error(), experiment.BlockIteration)
assert.Contains(t, labeled.Error(), `dependency "aurora"`)
unlabeled := config.ExpansionRequiresExperimentError{
ConfigPath: config.DefaultStackFile,
BlockType: "unit",
}
assert.Contains(t, unlabeled.Error(), experiment.BlockIteration)
assert.NotContains(t, unlabeled.Error(), `""`)
}
func TestDependencyExpandsForEach(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyString(t, `
dependency "aurora" {
expansion {
for_each = toset(["web", "api"])
}
config_path = "../${each.value}/aurora"
}
`)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 2)
keys := make([]string, 0, len(cfg.TerragruntDependencies))
paths := make([]string, 0, len(cfg.TerragruntDependencies))
for _, dep := range cfg.TerragruntDependencies {
require.NotNil(t, dep.Expansion)
assert.Equal(t, "aurora", dep.Name)
keys = append(keys, dep.Expansion.Key())
paths = append(paths, dep.ConfigPath.AsString())
}
assert.ElementsMatch(t, []string{"web", "api"}, keys)
assert.ElementsMatch(t, []string{"../web/aurora", "../api/aurora"}, paths)
}
func TestDependencyExpandsCount(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyString(t, `
dependency "shard" {
expansion {
count = 3
}
config_path = "../shard-${count.index}"
}
`)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 3)
for index, dep := range cfg.TerragruntDependencies {
require.NotNil(t, dep.Expansion)
assert.Equal(t, strconv.Itoa(index), dep.Expansion.Key())
assert.Equal(t, "../shard-"+strconv.Itoa(index), dep.ConfigPath.AsString())
}
}
// TestDependencyExpansionResolvesPerInstance covers attributes other than config_path
// resolving separately per element.
func TestDependencyExpansionResolvesPerInstance(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyString(t, `
locals {
regions = {
use1 = true
usw2 = false
}
}
dependency "vpc" {
expansion {
for_each = local.regions
}
config_path = "../${each.key}/vpc"
enabled = each.value
}
`)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 2)
enabled := map[string]bool{}
for _, dep := range cfg.TerragruntDependencies {
require.NotNil(t, dep.Enabled)
enabled[dep.Expansion.Key()] = *dep.Enabled
}
assert.Equal(t, map[string]bool{"use1": true, "usw2": false}, enabled)
}
// TestDisabledExpandedDependencySkipsOutputRetrieval points every instance at a directory
// that does not exist, so the parse only succeeds if none of them went looking for outputs.
func TestDisabledExpandedDependencySkipsOutputRetrieval(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
cfg, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "shard" {
expansion {
count = 2
}
enabled = false
config_path = "../no-such-unit-${count.index}"
}
`,
nil,
)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 2)
for _, dep := range cfg.TerragruntDependencies {
require.NotNil(t, dep.Enabled)
assert.False(t, *dep.Enabled)
assert.Nil(t, dep.RenderedOutputs)
}
}
func TestIncludeMergeKeepsEveryExpandedInstance(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
mergeStrategy string
}{
{name: "shallow merge"},
{name: "deep merge", mergeStrategy: `merge_strategy = "deep"`},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
dir := t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(dir, "network"), 0o755))
require.NoError(t, os.MkdirAll(filepath.Join(dir, "logging"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, "root.hcl"), []byte(`
dependencies {
paths = ["./network"]
}
dependency "vpc" {
enabled = false
config_path = "../vpc"
}
`), 0o644))
configPath := filepath.Join(dir, config.DefaultTerragruntConfigPath)
require.NoError(t, os.WriteFile(configPath, []byte(`
include "root" {
path = "root.hcl"
`+tc.mergeStrategy+`
}
dependencies {
paths = ["./logging"]
}
dependency "shard" {
expansion {
count = 3
}
enabled = false
config_path = "../shard-${count.index}"
}
`), 0o644))
ctx, pctx := newExpansionParsingContext(t, configPath)
cfg, err := config.ParseConfigFile(ctx, pctx, logger.CreateLogger(), configPath, nil)
require.NoError(t, err)
keys := make([]string, 0, len(cfg.TerragruntDependencies))
for _, dep := range cfg.TerragruntDependencies {
if dep.Name == "shard" {
keys = append(keys, dep.Expansion.Key())
}
}
assert.Equal(t, []string{"0", "1", "2"}, keys)
})
}
}
// TestExpandedDependencyCarriesItsOwnOutputConfig covers each instance resolving its own
// mock outputs.
func TestExpandedDependencyCarriesItsOwnOutputConfig(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
cfg, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "shard" {
expansion {
count = 2
}
config_path = "../shard-${count.index}"
skip_outputs = true
mock_outputs = {
id = "shard-${count.index}"
}
}
`,
nil,
)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 2)
outputs := map[string]string{}
for _, dep := range cfg.TerragruntDependencies {
require.NotNil(t, dep.MockOutputs)
outputs[dep.Expansion.Key()] = dep.MockOutputs.GetAttr("id").AsString()
}
assert.Equal(t, map[string]string{"0": "shard-0", "1": "shard-1"}, outputs)
}
func TestJSONConfigDecodesDependencies(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyJSONString(t, `
{"dependency": {"vpc": {"config_path": "../vpc", "enabled": false}}}
`)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 1)
assert.Equal(t, "vpc", cfg.TerragruntDependencies[0].Name)
assert.Equal(t, cty.StringVal("../vpc"), cfg.TerragruntDependencies[0].ConfigPath)
assert.Nil(t, cfg.TerragruntDependencies[0].Expansion)
}
func TestJSONConfigExpandsDependencies(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyJSONString(t, jsonDependencyWithExpansion)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 2)
paths := make([]string, 0, len(cfg.TerragruntDependencies))
for _, dep := range cfg.TerragruntDependencies {
paths = append(paths, dep.ConfigPath.AsString())
}
assert.Equal(t, []string{"../aurora-0", "../aurora-1"}, paths)
}
func TestJSONExpansionRequiresExperiment(t *testing.T) {
t.Parallel()
skipInExperimentMode(t)
ctx, pctx := newTestParsingContext(t, venvtest.NewOSWithEmptyEnv(), jsonConfigPath)
_, err := config.PartialParseConfigString(
ctx,
pctx.WithDecodeList(config.DependencyBlock),
logger.CreateLogger(),
jsonConfigPath,
jsonDependencyWithExpansion,
nil,
)
var typed config.ExpansionRequiresExperimentError
require.ErrorAs(t, err, &typed)
assert.Equal(t, "dependency", typed.BlockType)
assert.Equal(t, "aurora", typed.BlockLabel)
}
func TestUnknownBlockRemainsRejected(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
_, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
bogus "x" {
foo = 1
}
`,
nil,
)
require.Error(t, err)
}
func TestUnitAndStackExpandPerIterationElement(t *testing.T) {
t.Parallel()
stackCfg, err := parseStackString(t, unitWithExpansionHCL+stackWithExpansionHCL)
require.NoError(t, err)
require.Len(t, stackCfg.Units, 2)
require.Len(t, stackCfg.Stacks, 2)
unitPaths := map[string]string{}
for _, unit := range stackCfg.Units {
require.NotNil(t, unit.Expansion)
unitPaths[unit.Expansion.Key()] = unit.Path
}
assert.Equal(t, map[string]string{"web": "app/web", "api": "app/api"}, unitPaths)
stackPaths := map[string]string{}
for _, stack := range stackCfg.Stacks {
require.NotNil(t, stack.Expansion)
stackPaths[stack.Expansion.Key()] = stack.Path
}
assert.Equal(t, map[string]string{"0": "team/0", "1": "team/1"}, stackPaths)
}
func TestBlocksWithoutExpansionDecodeUnchanged(t *testing.T) {
t.Parallel()
cfg, err := parseDependencyString(t, `
dependency "vpc" {
config_path = "../vpc"
}
`)
require.NoError(t, err)
require.Len(t, cfg.TerragruntDependencies, 1)
dep := cfg.TerragruntDependencies[0]
assert.Nil(t, dep.Expansion)
assert.Equal(t, cty.StringVal("../vpc"), dep.ConfigPath)
stackCfg, err := parseStackString(t, `
unit "app" {
source = "./modules/app"
path = "app"
}
`)
require.NoError(t, err)
require.Len(t, stackCfg.Units, 1)
assert.Nil(t, stackCfg.Units[0].Expansion)
assert.Equal(t, "app", stackCfg.Units[0].Path)
}
func TestExpansionBlockRejectsMistypedAttribute(t *testing.T) {
t.Parallel()
testCases := []struct {
parse func(testing.TB, string) error
name string
cfg string
}{
{
name: "dependency",
parse: parseDependencyErr,
cfg: `
dependency "aurora" {
expansion {
foreach = toset(["web"])
}
config_path = "../aurora"
}
`,
},
{
name: "unit",
parse: parseStackErr,
cfg: `
unit "app" {
expansion {
foreach = toset(["web"])
}
source = "./modules/app"
path = "app"
}
`,
},
{
name: "stack",
parse: parseStackErr,
cfg: `
stack "team" {
expansion {
cuont = 2
}
source = "./stacks/team"
path = "team"
}
`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
require.Error(t, tc.parse(t, tc.cfg))
})
}
}
func TestIterationKeysAreNotSettableFromHCL(t *testing.T) {
t.Parallel()
_, err := parseDependencyString(t, `
dependency "aurora" {
each_key = "web"
config_path = "../aurora"
}
`)
require.Error(t, err)
stackCfg, err := parseStackString(t, `
unit "app" {
each_key = "web"
count_index = 0
source = "./modules/app"
path = "app"
}
`)
require.NoError(t, err)
require.Len(t, stackCfg.Units, 1)
// A unit absorbs unknown attributes into its remainder rather than rejecting them,
// so what it can be held to is that writing them leaves no expansion state.
assert.Nil(t, stackCfg.Units[0].Expansion)
}
// TestDependencyCtyShapeExcludesExpansionMetadata pins the attribute set a dependency
// exposes to read_terragrunt_config and render, which a cty tag on expansion metadata
// would widen for every user, experiment or not.
func TestDependencyCtyShapeExcludesExpansionMetadata(t *testing.T) {
t.Parallel()
value, err := config.GoTypeToCty(config.Dependency{
Name: "vpc",
ConfigPath: cty.StringVal("../vpc"),
})
require.NoError(t, err)
attrs := make([]string, 0, len(value.Type().AttributeTypes()))
for name := range value.Type().AttributeTypes() {
attrs = append(attrs, name)
}
assert.ElementsMatch(t, []string{
"name",
"config_path",
"enabled",
"skip",
"mock_outputs",
"mock_outputs_allowed_terraform_commands",
"mock_outputs_merge_with_state",
"mock_outputs_merge_strategy_with_state",
"outputs",
"inputs",
}, attrs)
}
// TestDependencyOutputsAddressedByInstanceKey pins the address an expanded dependency answers to,
// alongside an unexpanded block in the same config to hold its unkeyed address steady.
func TestDependencyOutputsAddressedByInstanceKey(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
cfg, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "vpc" {
config_path = "../vpc"
skip_outputs = true
mock_outputs = {
id = "vpc-main"
}
}
dependency "aurora" {
expansion {
for_each = toset(["web", "api"])
}
config_path = "../aurora-${each.key}"
skip_outputs = true
mock_outputs = {
id = "aurora-${each.key}"
}
}
dependency "shard" {
expansion {
count = 2
}
config_path = "../shard-${count.index}"
skip_outputs = true
mock_outputs = {
id = "shard-${count.index}"
}
}
inputs = {
vpc_id = dependency.vpc.outputs.id
vpc_outputs = dependency.vpc.outputs
web = dependency.aurora["web"].outputs.id
api = dependency.aurora["api"].outputs.id
first = dependency.shard["0"].outputs.id
second = dependency.shard["1"].outputs.id
unquoted = dependency.shard[0].outputs.id
}
`,
nil,
)
require.NoError(t, err)
assert.Equal(t, map[string]any{
"vpc_id": "vpc-main",
"vpc_outputs": map[string]any{"id": "vpc-main"},
"web": "aurora-web",
"api": "aurora-api",
"first": "shard-0",
"second": "shard-1",
"unquoted": "shard-0",
}, cfg.Inputs)
}
// TestDependencyOutputsRejectExpandedBlockWithoutKey holds the keyed level to being the only
// address for an expanded block, since a config that reached past it would be reading an
// arbitrary instance.
func TestDependencyOutputsRejectExpandedBlockWithoutKey(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
_, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "aurora" {
expansion {
for_each = toset(["web"])
}
config_path = "../aurora-${each.key}"
skip_outputs = true
mock_outputs = {
id = "aurora-${each.key}"
}
}
inputs = {
id = dependency.aurora.outputs.id
}
`,
nil,
)
var diags hcl.Diagnostics
require.ErrorAs(t, err, &diags)
require.Len(t, diags, 1)
// Naming the diagnostic keeps the test from passing on any other evaluation failure the
// fixture might grow.
assert.Equal(t, "Unsupported attribute", diags[0].Summary)
}
// TestDependencyOutputsEncodeDivergentSchemasPerKey covers instances whose outputs share no
// schema, so encoding cannot lean on the keys agreeing on a type.
func TestDependencyOutputsEncodeDivergentSchemasPerKey(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
cfg, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "mixed" {
expansion {
for_each = {
a = { id = "mixed-a" }
b = { name = "mixed-b", size = 3 }
}
}
config_path = "../mixed-${each.key}"
skip_outputs = true
mock_outputs = each.value
}
inputs = {
a_id = dependency.mixed["a"].outputs.id
b_name = dependency.mixed["b"].outputs.name
b_size = dependency.mixed["b"].outputs.size
}
`,
nil,
)
require.NoError(t, err)
assert.Equal(t, map[string]any{
"a_id": "mixed-a",
"b_name": "mixed-b",
"b_size": json.Number("3"),
}, cfg.Inputs)
}
// TestDependencyInstanceKeysMatchAddressableKeys ties the key the parser reports for an instance
// to the key a config writes to reach it.
func TestDependencyInstanceKeysMatchAddressableKeys(t *testing.T) {
t.Parallel()
ctx, pctx := newExpansionParsingContext(t, config.DefaultTerragruntConfigPath)
cfg, err := config.ParseConfigString(
ctx,
pctx,
logger.CreateLogger(),
config.DefaultTerragruntConfigPath,
`
dependency "numbered" {
expansion {
for_each = toset([1, 2])
}
config_path = "../numbered-${each.key}"
skip_outputs = true
mock_outputs = {
engine_key = each.key
}
}
dependency "shard" {
expansion {
count = 2
}