Skip to content

Commit

Permalink
feat(misconf): iterator argument support for dynamic blocks (#7236)
Browse files Browse the repository at this point in the history
Signed-off-by: nikpivkin <[email protected]>
Co-authored-by: simar7 <[email protected]>
  • Loading branch information
nikpivkin and simar7 authored Aug 7, 2024
1 parent f0ed5e4 commit fe92072
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pkg/iac/scanners/terraform/parser/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,18 @@ func (e *evaluator) expandBlockForEaches(blocks terraform.Blocks, isDynamic bool
ctx.Set(idx, block.TypeLabel(), "key")
ctx.Set(val, block.TypeLabel(), "value")

if isDynamic {
if iterAttr := block.GetAttribute("iterator"); iterAttr.IsNotNil() {
refs := iterAttr.AllReferences()
if len(refs) == 1 {
ctx.Set(idx, refs[0].TypeLabel(), "key")
ctx.Set(val, refs[0].TypeLabel(), "value")
} else {
e.debug.Log("Ignoring iterator attribute in dynamic block, expected one reference but got %d", len(refs))
}
}
}

forEachFiltered = append(forEachFiltered, clone)

values := clone.Values()
Expand Down
36 changes: 36 additions & 0 deletions pkg/iac/scanners/terraform/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1746,6 +1746,42 @@ func TestTFVarsFileDoesNotExist(t *testing.T) {
assert.ErrorContains(t, err, "file does not exist")
}

func TestDynamicWithIterator(t *testing.T) {
fsys := fstest.MapFS{
"main.tf": &fstest.MapFile{
Data: []byte(`resource "aws_s3_bucket" "this" {
dynamic versioning {
for_each = [true]
iterator = ver
content {
enabled = ver.value
}
}
}`),
},
}

parser := New(
fsys, "",
OptionStopOnHCLError(true),
OptionWithDownloads(false),
)
require.NoError(t, parser.ParseFS(context.TODO(), "."))

modules, _, err := parser.EvaluateAll(context.TODO())
require.NoError(t, err)

assert.Len(t, modules, 1)

buckets := modules.GetResourcesByType("aws_s3_bucket")
assert.Len(t, buckets, 1)

attr, _ := buckets[0].GetNestedAttribute("versioning.enabled")

assert.True(t, attr.Value().True())
}

func Test_AWSRegionNameDefined(t *testing.T) {

fs := testutil.CreateFS(t, map[string]string{
Expand Down

0 comments on commit fe92072

Please sign in to comment.