Skip to content

feat: terraform parser option to set current working directory #8909

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

Merged
merged 2 commits into from
May 27, 2025
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
6 changes: 6 additions & 0 deletions pkg/iac/scanners/terraform/parser/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ func OptionWithLogger(log *log.Logger) Option {
}
}

func OptionWithWorkingDirectoryPath(cwd string) Option {
return func(p *Parser) {
p.cwd = cwd
}
}

func OptionsWithTfVars(vars map[string]cty.Value) Option {
return func(p *Parser) {
p.tfvars = vars
Expand Down
14 changes: 11 additions & 3 deletions pkg/iac/scanners/terraform/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ type Parser struct {
fsMap map[string]fs.FS
configsFS fs.FS
skipPaths []string
// cwd is optional, if left to empty string, 'os.Getwd'
// will be used for populating 'path.cwd' in terraform.
cwd string
}

// New creates a new Parser
Expand Down Expand Up @@ -293,9 +296,14 @@ func (p *Parser) Load(_ context.Context) (*evaluator, error) {
)
}

workingDir, err := os.Getwd()
if err != nil {
return nil, err
var workingDir string
if p.cwd != "" {
workingDir = p.cwd
} else {
workingDir, err = os.Getwd()
if err != nil {
return nil, err
}
}

p.logger.Debug("Working directory for module evaluation", log.FilePath(workingDir))
Expand Down
23 changes: 23 additions & 0 deletions pkg/iac/scanners/terraform/parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2790,3 +2790,26 @@ func TestInstancedLogger(t *testing.T) {
t.Log(buf.String()) // Helpful for debugging
}
}

func TestProvidedWorkingDirectory(t *testing.T) {
const fakeCwd = "/some/path"
fsys := testutil.CreateFS(t, map[string]string{
"main.tf": `
resource "foo" "bar" {
cwd = path.cwd
}
`,
})

parser := New(fsys, "", OptionWithWorkingDirectoryPath(fakeCwd))
err := parser.ParseFS(t.Context(), ".")
require.NoError(t, err)

modules, err := parser.EvaluateAll(t.Context())
require.NoError(t, err)

require.Len(t, modules, 1)
foo := modules[0].GetResourcesByType("foo")[0]
attr := foo.GetAttribute("cwd")
require.Equal(t, fakeCwd, attr.Value().AsString())
}