From f27c236d6e155cb366aeef619b6ea96d20fb93da Mon Sep 17 00:00:00 2001 From: Nikita Pivkin Date: Wed, 10 Jul 2024 10:02:40 +0700 Subject: [PATCH] fix(misconf): do not evaluate TF when a load error occurs (#7109) Signed-off-by: nikpivkin --- pkg/iac/scanners/terraform/parser/parser.go | 3 +++ .../scanners/terraform/parser/parser_test.go | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/pkg/iac/scanners/terraform/parser/parser.go b/pkg/iac/scanners/terraform/parser/parser.go index aec5ce0c31d7..fa511fed54c2 100644 --- a/pkg/iac/scanners/terraform/parser/parser.go +++ b/pkg/iac/scanners/terraform/parser/parser.go @@ -268,7 +268,10 @@ func (p *Parser) EvaluateAll(ctx context.Context) (terraform.Modules, cty.Value, e, err := p.Load(ctx) if errors.Is(err, ErrNoFiles) { return nil, cty.NilVal, nil + } else if err != nil { + return nil, cty.NilVal, err } + modules, fsMap := e.EvaluateAll(ctx) p.debug.Log("Finished parsing module '%s'.", p.moduleName) p.fsMap = fsMap diff --git a/pkg/iac/scanners/terraform/parser/parser_test.go b/pkg/iac/scanners/terraform/parser/parser_test.go index 3d25b5518b46..10232b007fd9 100644 --- a/pkg/iac/scanners/terraform/parser/parser_test.go +++ b/pkg/iac/scanners/terraform/parser/parser_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "sort" "testing" + "testing/fstest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1725,3 +1726,22 @@ func Test_LoadLocalCachedModule(t *testing.T) { bucketName := buckets[0].GetAttribute("bucket").Value().AsString() assert.Equal(t, "my-s3-bucket", bucketName) } + +func TestTFVarsFileDoesNotExist(t *testing.T) { + fsys := fstest.MapFS{ + "main.tf": &fstest.MapFile{ + Data: []byte(``), + }, + } + + parser := New( + fsys, "", + OptionStopOnHCLError(true), + OptionWithDownloads(false), + OptionWithTFVarsPaths("main.tfvars"), + ) + require.NoError(t, parser.ParseFS(context.TODO(), ".")) + + _, _, err := parser.EvaluateAll(context.TODO()) + assert.ErrorContains(t, err, "file does not exist") +}