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): allow nullable value for default values of vars #1370

Merged
merged 1 commit into from
Jul 6, 2023
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
2 changes: 1 addition & 1 deletion pkg/scanners/terraform/parser/evaluator.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ func (e *evaluator) evaluateVariable(b *terraform.Block) (cty.Value, error) {
return cty.NilVal, fmt.Errorf("cannot resolve variable with no attributes")
}
if def, exists := attributes["default"]; exists {
return def.Value(), nil
return def.NullableValue(), nil
}
return cty.NilVal, fmt.Errorf("no value found")
}
Expand Down
33 changes: 33 additions & 0 deletions pkg/scanners/terraform/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,3 +633,36 @@ module "registry" {
require.NoError(t, err)
require.Len(t, modules, 2)
}

func Test_NullDefaultValueForVar(t *testing.T) {
fs := testutil.CreateFS(t, map[string]string{
"test.tf": `
variable "bucket_name" {
type = string
default = null
}

resource "aws_s3_bucket" "default" {
bucket = var.bucket_name != null ? var.bucket_name : "default"
}
`,
})

parser := New(fs, "", OptionStopOnHCLError(true))
if err := parser.ParseFS(context.TODO(), "."); err != nil {
t.Fatal(err)
}
modules, _, err := parser.EvaluateAll(context.TODO())
require.NoError(t, err)
require.Len(t, modules, 1)

rootModule := modules[0]

blocks := rootModule.GetResourcesByType("aws_s3_bucket")
require.Len(t, blocks, 1)
block := blocks[0]

attr := block.GetAttribute("bucket")
require.NotNil(t, attr)
assert.Equal(t, "default", attr.Value().AsString())
}
17 changes: 17 additions & 0 deletions pkg/terraform/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,23 @@ func (a *Attribute) Value() (ctyVal cty.Value) {
return ctyVal
}

// Allows a null value for a variable https://developer.hashicorp.com/terraform/language/expressions/types#null
func (a *Attribute) NullableValue() (ctyVal cty.Value) {
if a == nil {
return cty.NilVal
}
defer func() {
if err := recover(); err != nil {
ctyVal = cty.NilVal
}
}()
ctyVal, _ = a.hclAttribute.Expr.Value(a.ctx.Inner())
if !ctyVal.IsKnown() {
return cty.NilVal
}
return ctyVal
}

func (a *Attribute) Name() string {
if a == nil {
return ""
Expand Down