@@ -7,13 +7,15 @@ import (
77 "io/fs"
88 "log/slog"
99 "path/filepath"
10+ "strings"
1011
1112 "github.com/aquasecurity/trivy/pkg/iac/scanners/terraform/parser"
1213 "github.com/hashicorp/hcl/v2"
1314 "github.com/zclconf/go-cty/cty"
1415 ctyjson "github.com/zclconf/go-cty/cty/json"
1516
1617 "github.com/coder/preview/hclext"
18+ "github.com/coder/preview/tfvars"
1719 "github.com/coder/preview/types"
1820)
1921
@@ -26,6 +28,7 @@ type Input struct {
2628 ParameterValues map [string ]string
2729 Owner types.WorkspaceOwner
2830 Logger * slog.Logger
31+ TFVars map [string ]cty.Value
2932}
3033
3134type Output struct {
@@ -96,7 +99,18 @@ func Preview(ctx context.Context, input Input, dir fs.FS) (output *Output, diagn
9699 }
97100 }
98101
99- planHook , err := planJSONHook (dir , input )
102+ variableValues , err := tfvars .LoadTFVars (dir , varFiles )
103+ if err != nil {
104+ return nil , hcl.Diagnostics {
105+ {
106+ Severity : hcl .DiagError ,
107+ Summary : "Failed to load tfvars from files" ,
108+ Detail : err .Error (),
109+ },
110+ }
111+ }
112+
113+ planHook , err := PlanJSONHook (dir , input )
100114 if err != nil {
101115 return nil , hcl.Diagnostics {
102116 {
@@ -121,6 +135,11 @@ func Preview(ctx context.Context, input Input, dir fs.FS) (output *Output, diagn
121135 logger := input .Logger
122136 if logger == nil { // Default to discarding logs
123137 logger = slog .New (slog .DiscardHandler )
138+ }
139+
140+ // Override with user supplied variables
141+ for k , v := range input .TFVars {
142+ variableValues [k ] = v
124143 }
125144
126145 // moduleSource is "" for a local module
@@ -129,11 +148,12 @@ func Preview(ctx context.Context, input Input, dir fs.FS) (output *Output, diagn
129148 parser .OptionStopOnHCLError (false ),
130149 parser .OptionWithDownloads (false ),
131150 parser .OptionWithSkipCachedModules (true ),
132- parser .OptionWithTFVarsPaths (varFiles ... ),
133151 parser .OptionWithEvalHook (planHook ),
134152 parser .OptionWithEvalHook (ownerHook ),
135- parser .OptionWithWorkingDirectoryPath ("/" ),
136- parser .OptionWithEvalHook (parameterContextsEvalHook (input )),
153+ parser .OptionWithEvalHook (ParameterContextsEvalHook (input )),
154+ // 'OptionsWithTfVars' cannot be set with 'OptionWithTFVarsPaths'. So load the
155+ // tfvars from the files ourselves and merge with the user-supplied tf vars.
156+ parser .OptionsWithTfVars (variableValues ),
137157 )
138158
139159 err = p .ParseFS (ctx , "." )
@@ -203,7 +223,7 @@ func tfVarFiles(path string, dir fs.FS) ([]string, error) {
203223 files = append (files , newFiles ... )
204224 }
205225
206- if filepath .Ext (entry .Name ()) == ".tfvars" {
226+ if filepath .Ext (entry .Name ()) == ".tfvars" || strings . HasSuffix ( entry . Name (), ".tfvars.json" ) {
207227 files = append (files , filepath .Join (path , entry .Name ()))
208228 }
209229 }
0 commit comments