Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(terraform): set null value as fallback for missing variables #7669

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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