From 6e268f4759b1df821a848d39f4eab716f1109600 Mon Sep 17 00:00:00 2001 From: nikpivkin Date: Fri, 13 Dec 2024 15:22:01 +0600 Subject: [PATCH] fix(misconf): allow null values only for tf variables Signed-off-by: nikpivkin --- .../scanners/terraform/parser/load_module.go | 2 +- .../scanners/terraform/parser/parser_test.go | 26 +++++++++++++++++++ pkg/iac/terraform/block.go | 14 +++++++++- 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/pkg/iac/scanners/terraform/parser/load_module.go b/pkg/iac/scanners/terraform/parser/load_module.go index 595e1b02c33e..878bf075baec 100644 --- a/pkg/iac/scanners/terraform/parser/load_module.go +++ b/pkg/iac/scanners/terraform/parser/load_module.go @@ -25,7 +25,7 @@ type ModuleDefinition struct { } func (d *ModuleDefinition) inputVars() map[string]cty.Value { - inputs := d.Definition.Values().AsValueMap() + inputs := d.Definition.NullableValues().AsValueMap() if inputs == nil { return make(map[string]cty.Value) } diff --git a/pkg/iac/scanners/terraform/parser/parser_test.go b/pkg/iac/scanners/terraform/parser/parser_test.go index e88dd017d2fa..e7ffa3230be3 100644 --- a/pkg/iac/scanners/terraform/parser/parser_test.go +++ b/pkg/iac/scanners/terraform/parser/parser_test.go @@ -2161,3 +2161,29 @@ resource "foo" "this" { }) } } + +func TestAttrRefToNullVariable(t *testing.T) { + fsys := fstest.MapFS{ + "main.tf": &fstest.MapFile{Data: []byte(`variable "name" { + type = string + default = null +} + +resource "aws_s3_bucket" "example" { + bucket = var.name +}`)}, + } + + parser := New(fsys, "", OptionStopOnHCLError(true)) + + require.NoError(t, parser.ParseFS(context.TODO(), ".")) + + _, err := parser.Load(context.TODO()) + require.NoError(t, err) + + modules, _, err := parser.EvaluateAll(context.TODO()) + require.NoError(t, err) + + val := modules.GetResourcesByType("aws_s3_bucket")[0].GetAttribute("bucket").GetRawValue() + assert.Nil(t, val) +} diff --git a/pkg/iac/terraform/block.go b/pkg/iac/terraform/block.go index d57d4331c1c4..4e9f794e914c 100644 --- a/pkg/iac/terraform/block.go +++ b/pkg/iac/terraform/block.go @@ -569,13 +569,25 @@ func (b *Block) Attributes() map[string]*Attribute { return attributes } +func (b *Block) NullableValues() cty.Value { + return b.values(true) +} + func (b *Block) Values() cty.Value { + return b.values(false) +} + +func (b *Block) values(allowNull bool) cty.Value { values := createPresetValues(b) for _, attribute := range b.GetAttributes() { if attribute.Name() == "for_each" { continue } - values[attribute.Name()] = attribute.NullableValue() + if allowNull { + values[attribute.Name()] = attribute.NullableValue() + } else { + values[attribute.Name()] = attribute.Value() + } } return cty.ObjectVal(postProcessValues(b, values)) }