Skip to content

Commit 611558e

Browse files
authoredNov 8, 2024··
fix(terraform): set null value as fallback for missing variables (#7669)
1 parent 99b2db3 commit 611558e

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
 

‎pkg/iac/scanners/terraform/parser/parser.go

+9
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ func (p *Parser) Load(ctx context.Context) (*evaluator, error) {
217217
"Variable values was not found in the environment or variable files. Evaluating may not work correctly.",
218218
log.String("variables", strings.Join(missingVars, ", ")),
219219
)
220+
setNullMissingVariableValues(inputVars, missingVars)
220221
}
221222
}
222223

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

272+
// Set null values for missing variables, to allow expressions using them to be
273+
// still be possibly evaluated to a value different than null.
274+
func setNullMissingVariableValues(inputVars map[string]cty.Value, missingVars []string) {
275+
for _, missingVar := range missingVars {
276+
inputVars[missingVar] = cty.NullVal(cty.DynamicPseudoType)
277+
}
278+
}
279+
271280
func (p *Parser) EvaluateAll(ctx context.Context) (terraform.Modules, cty.Value, error) {
272281

273282
e, err := p.Load(ctx)

‎pkg/iac/scanners/terraform/parser/parser_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -1801,6 +1801,36 @@ resource "test" "fileset-func" {
18011801
assert.Equal(t, []string{"a.py", "path/b.py"}, attr.GetRawValue())
18021802
}
18031803

1804+
func TestExprWithMissingVar(t *testing.T) {
1805+
files := map[string]string{
1806+
"main.tf": `
1807+
variable "v" {
1808+
type = string
1809+
}
1810+
1811+
resource "test" "values" {
1812+
s = "foo-${var.v}"
1813+
l1 = ["foo", var.v]
1814+
l2 = concat(["foo"], [var.v])
1815+
d1 = {foo = var.v}
1816+
d2 = merge({"foo": "bar"}, {"baz": var.v})
1817+
}
1818+
`,
1819+
}
1820+
1821+
resources := parse(t, files).GetResourcesByType("test")
1822+
require.Len(t, resources, 1)
1823+
1824+
s_attr := resources[0].GetAttribute("s")
1825+
require.NotNil(t, s_attr)
1826+
assert.Equal(t, "foo-", s_attr.GetRawValue())
1827+
1828+
for _, name := range []string{"l1", "l2", "d1", "d2"} {
1829+
attr := resources[0].GetAttribute(name)
1830+
require.NotNil(t, attr)
1831+
}
1832+
}
1833+
18041834
func TestVarTypeShortcut(t *testing.T) {
18051835
files := map[string]string{
18061836
"main.tf": `

0 commit comments

Comments
 (0)
Please sign in to comment.