Skip to content

Commit

Permalink
fix(terraform): allow nullable value for default values of vars (#1370)
Browse files Browse the repository at this point in the history
  • Loading branch information
nikpivkin authored Jul 6, 2023
1 parent 5125040 commit e87deb0
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
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

0 comments on commit e87deb0

Please sign in to comment.