Skip to content

Commit bee4dda

Browse files
committed
Merge remote-tracking branch 'coder/stevenmasley/cwd' into dynamic-parameters
2 parents 3c72a59 + fe2237b commit bee4dda

File tree

3 files changed

+40
-3
lines changed

3 files changed

+40
-3
lines changed

pkg/iac/scanners/terraform/parser/option.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ func OptionWithLogger(log *log.Logger) Option {
3434
}
3535
}
3636

37+
func OptionWithWorkingDirectoryPath(cwd string) Option {
38+
return func(p *Parser) {
39+
p.cwd = cwd
40+
}
41+
}
42+
3743
func OptionsWithTfVars(vars map[string]cty.Value) Option {
3844
return func(p *Parser) {
3945
p.tfvars = vars

pkg/iac/scanners/terraform/parser/parser.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ type Parser struct {
5353
configsFS fs.FS
5454
skipPaths []string
5555
stepHooks []EvaluateStepHook
56+
// cwd is optional, if left to empty string, 'os.Getwd'
57+
// will be used for populating 'path.cwd' in terraform.
58+
cwd string
5659
}
5760

5861
// New creates a new Parser
@@ -295,9 +298,14 @@ func (p *Parser) Load(_ context.Context) (*evaluator, error) {
295298
)
296299
}
297300

298-
workingDir, err := os.Getwd()
299-
if err != nil {
300-
return nil, err
301+
var workingDir string
302+
if p.cwd != "" {
303+
workingDir = p.cwd
304+
} else {
305+
workingDir, err = os.Getwd()
306+
if err != nil {
307+
return nil, err
308+
}
301309
}
302310

303311
p.logger.Debug("Working directory for module evaluation", log.FilePath(workingDir))

pkg/iac/scanners/terraform/parser/parser_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3013,3 +3013,26 @@ func TestInstancedLogger(t *testing.T) {
30133013
t.Log(buf.String()) // Helpful for debugging
30143014
}
30153015
}
3016+
3017+
func TestProvidedWorkingDirectory(t *testing.T) {
3018+
const fakeCwd = "/some/path"
3019+
fsys := testutil.CreateFS(t, map[string]string{
3020+
"main.tf": `
3021+
resource "foo" "bar" {
3022+
cwd = path.cwd
3023+
}
3024+
`,
3025+
})
3026+
3027+
parser := New(fsys, "", OptionWithWorkingDirectoryPath(fakeCwd))
3028+
err := parser.ParseFS(t.Context(), ".")
3029+
require.NoError(t, err)
3030+
3031+
modules, err := parser.EvaluateAll(t.Context())
3032+
require.NoError(t, err)
3033+
3034+
require.Len(t, modules, 1)
3035+
foo := modules[0].GetResourcesByType("foo")[0]
3036+
attr := foo.GetAttribute("cwd")
3037+
require.Equal(t, fakeCwd, attr.Value().AsString())
3038+
}

0 commit comments

Comments
 (0)