Skip to content

Commit

Permalink
fix(terraform): set null value as fallback for missing variables
Browse files Browse the repository at this point in the history
  • Loading branch information
albertodonato committed Oct 8, 2024
1 parent fdf203c commit 0b6dcd4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/iac/scanners/terraform/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,7 @@ func (p *Parser) Load(ctx context.Context) (*evaluator, error) {
"Variable values was not found in the environment or variable files. Evaluating may not work correctly.",
log.String("variables", strings.Join(missingVars, ", ")),
)
setNullMissingVariableValues(inputVars, missingVars)
}
}

Expand Down Expand Up @@ -268,6 +269,14 @@ func missingVariableValues(blocks terraform.Blocks, inputVars map[string]cty.Val
return missing
}

// Set null values for missing variables, to allow expressions using them to be
// still be possibly evaluated to a value different than null.
func setNullMissingVariableValues(inputVars map[string]cty.Value, missingVars []string) {
for _, missingVar := range missingVars {
inputVars[missingVar] = cty.NullVal(cty.DynamicPseudoType)
}
}

func (p *Parser) EvaluateAll(ctx context.Context) (terraform.Modules, cty.Value, error) {

e, err := p.Load(ctx)
Expand Down
30 changes: 30 additions & 0 deletions pkg/iac/scanners/terraform/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1671,6 +1671,36 @@ resource "test" "fileset-func" {
assert.Equal(t, []string{"a.py", "path/b.py"}, attr.GetRawValue())
}

func TestExprWithMissingVar(t *testing.T) {
files := map[string]string{
"main.tf": `
variable "v" {
type = string
}
resource "test" "values" {
s = "foo-${var.v}"
l1 = ["foo", var.v]
l2 = concat(["foo"], [var.v])
d1 = {foo = var.v}
d2 = merge({"foo": "bar"}, {"baz": var.v})
}
`,
}

resources := parse(t, files).GetResourcesByType("test")
require.Len(t, resources, 1)

s_attr := resources[0].GetAttribute("s")
require.NotNil(t, s_attr)
assert.Equal(t, "foo-", s_attr.GetRawValue())

for _, name := range []string{"l1", "l2", "d1", "d2"} {
attr := resources[0].GetAttribute(name)
require.NotNil(t, attr)
}
}

func TestVarTypeShortcut(t *testing.T) {
files := map[string]string{
"main.tf": `
Expand Down

0 comments on commit 0b6dcd4

Please sign in to comment.