Skip to content

Commit af50d84

Browse files
committed
more comments, cosmetic changes
1 parent a9e8fca commit af50d84

14 files changed

Lines changed: 39 additions & 50 deletions

File tree

internal/backend/local/backend_apply.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ func (b *Local) opApply(
9797
// If we weren't given a plan, then we refresh/plan
9898
if op.PlanFile == nil {
9999
// set the policy client to nil for the plan preceding apply
100+
// so that policy evaluation is skipped during the plan.
100101
lr.PlanOpts.PolicyClient = nil
101102
combinedPlanApply = true
102103
// Perform the plan
@@ -114,8 +115,6 @@ func (b *Local) opApply(
114115
if plan != nil && (len(plan.Changes.Resources) != 0 || len(plan.Changes.Outputs) != 0) {
115116
op.View.Plan(plan, schemas)
116117
}
117-
// Report all policy results that may have accumulated during the plan
118-
op.View.PolicyResults(plan.PolicyResults)
119118
op.ReportResult(runningOp, diags)
120119
return
121120
}
@@ -427,9 +426,6 @@ func (b *Local) opApply(
427426
var applyState *states.State
428427
var applyDiags tfdiags.Diagnostics
429428

430-
// We use a new store for the apply policy results, as objects that failed during the plan policy
431-
// evaluation may have updated data which yields a different policy evaluation result.
432-
policyResults := plans.NewPolicyResults()
433429
doneCh := make(chan struct{})
434430
go func() {
435431
defer logging.PanicHandler()
@@ -438,9 +434,9 @@ func (b *Local) opApply(
438434
log.Printf("[INFO] backend/local: apply calling Apply")
439435
applyState, applyDiags = lr.Core.Apply(plan, lr.Config, &terraform.ApplyOpts{
440436
SetVariables: applyTimeValues,
441-
Locks: providerLocksSnapshot(op.DependencyLocks),
437+
ProviderLocks: providerLocksSnapshot(op.DependencyLocks),
442438
PolicyClient: lr.PolicyClient,
443-
PolicyResults: policyResults,
439+
PolicyResults: plan.PolicyResults,
444440
})
445441
}()
446442

@@ -450,7 +446,7 @@ func (b *Local) opApply(
450446
diags = diags.Append(applyDiags)
451447

452448
// Print the policy results we found during apply
453-
op.View.PolicyResults(policyResults)
449+
op.View.PolicyResults(plan.PolicyResults)
454450

455451
// Even on error with an empty state, the state value should not be nil.
456452
// Return early here to prevent corrupting any existing state.

internal/backend/local/backend_local.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ func (b *Local) localRunDirect(op *backendrun.Operation, run *backendrun.LocalRu
188188
GenerateConfigPath: op.GenerateConfigOut,
189189
DeferralAllowed: op.DeferralAllowed,
190190
Query: op.Query,
191-
Locks: providerLocksSnapshot(op.DependencyLocks),
191+
ProviderLocks: providerLocksSnapshot(op.DependencyLocks),
192192
PolicyClient: run.PolicyClient,
193193
}
194194
run.PlanOpts = planOpts
@@ -213,14 +213,14 @@ func (b *Local) localRunDirect(op *backendrun.Operation, run *backendrun.LocalRu
213213
)
214214
diags = diags.Append(buildDiags)
215215
if buildDiags.HasErrors() {
216-
return nil, nil, diags
216+
return run, nil, diags
217217
}
218218
run.Config = config
219219

220220
snapDiags := op.ConfigLoader.AddRootModuleToSnapshot(configSnap, op.ConfigDir)
221221
diags = diags.Append(snapDiags)
222222
if snapDiags.HasErrors() {
223-
return nil, nil, diags
223+
return run, nil, diags
224224
}
225225

226226
if errs := config.VerifyDependencySelections(op.DependencyLocks); len(errs) > 0 {

internal/command/apply.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ func (c *ApplyCommand) Run(rawArgs []string) int {
109109
if len(c.policyPaths) > 0 {
110110
var policyDiags policy.Diagnostics
111111
opReq.PolicyClient, policyDiags = c.PolicyClient(context.Background(), c.policyPaths)
112-
// if there has been any errors when setting up the policy client, we'll want to log them
112+
// if there has been any errors when setting up the policy client, we'll log them
113113
if opReq.View != nil && policyDiags != nil {
114114
opReq.View.PolicyResults(&plans.PolicyResults{Diagnostics: policyDiags})
115115
}

internal/command/arguments/query.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,6 @@ type Query struct {
2121
// the found resources in the query and which path the generated file should
2222
// be written to.
2323
GenerateConfigPath string
24-
25-
// PolicyPath contains an optional path to any defined policies that should
26-
// be applied for this plan operation.
27-
PolicyPaths []string
2824
}
2925

3026
func ParseQuery(args []string) (*Query, tfdiags.Diagnostics) {
@@ -44,7 +40,6 @@ func ParseQuery(args []string) (*Query, tfdiags.Diagnostics) {
4440
query.Vars.varFiles = &varFilesFlags
4541
cmdFlags.Var(query.Vars.vars, "var", "var")
4642
cmdFlags.Var(query.Vars.varFiles, "var-file", "var-file")
47-
cmdFlags.Var((*FlagStringSlice)(&query.PolicyPaths), "policies", "policies")
4843

4944
var json bool
5045
cmdFlags.BoolVar(&json, "json", false, "json")

internal/command/format/diagnostic.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ func (f *snippetFormatter) write() {
230230
diag := f.diag
231231
buf := f.buf
232232

233+
// if the diagnostic has a policy range, then it contains policy-specific information
234+
// and we will write that first.
233235
snippetPrefix := " on"
234236
if diag.PolicyRange != nil {
235237

internal/command/meta_policy.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ func (c *Meta) PolicyClient(ctx context.Context, policyPaths []string) (policy.C
3535

3636
var diags policy.Diagnostics
3737
client, err := policy.Connect(ctx)
38-
if client == nil {
38+
if err != nil {
3939
diags = append(diags, policy.NewErrorDiagnostic(
4040
"Failed to connect to policy engine",
4141
fmt.Sprintf("Failed to connect to policy engine: %s.", err),
@@ -50,6 +50,7 @@ func (c *Meta) PolicyClient(ctx context.Context, policyPaths []string) (policy.C
5050
if srv, ok := client.(policy.CallbackService); ok {
5151
callbackServer, cbDiags := srv.RegisterCallbackService(ctx)
5252
if cbDiags != nil {
53+
client.Stop()
5354
return nil, cbDiags
5455
}
5556
callbackServiceID = callbackServer.ID
@@ -65,6 +66,7 @@ func (c *Meta) PolicyClient(ctx context.Context, policyPaths []string) (policy.C
6566
for _, config := range resp.ServerConfigurations() {
6667
version, err := constraints.ParseRubyStyleMulti(config.RequiredVersion)
6768
if err != nil {
69+
client.Stop()
6870
diags = append(diags, policy.NewErrorDiagnostic(
6971
"Failed to validate required Terraform version",
7072
fmt.Sprintf("The policy file %s had a Terraform version constraint that could not be parsed: %s.", config.File, err),

internal/command/query.go

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ func (c *QueryCommand) Run(rawArgs []string) int {
118118
}
119119

120120
// Build the operation request
121-
opReq, opDiags := c.OperationRequest(be, view, args.ViewType, args.GenerateConfigPath, args.PolicyPaths)
121+
opReq, opDiags := c.OperationRequest(be, view, args.ViewType, args.GenerateConfigPath)
122122
diags = diags.Append(opDiags)
123123
if diags.HasErrors() {
124124
view.Diagnostics(diags)
@@ -164,7 +164,6 @@ func (c *QueryCommand) OperationRequest(
164164
view views.Query,
165165
viewType arguments.ViewType,
166166
generateConfigOut string,
167-
policyPaths []string,
168167
) (*backendrun.Operation, tfdiags.Diagnostics) {
169168
var diags tfdiags.Diagnostics
170169

@@ -176,16 +175,6 @@ func (c *QueryCommand) OperationRequest(
176175
opReq.GenerateConfigOut = generateConfigOut
177176
opReq.View = view.Operation()
178177
opReq.Query = true
179-
opReq.PolicyPaths = policyPaths
180-
181-
if !c.AllowExperimentalFeatures && len(policyPaths) > 0 {
182-
diags = diags.Append(tfdiags.Sourceless(
183-
tfdiags.Error,
184-
"Failed to parse command-line flags",
185-
"The -policies flag is only valid in experimental builds of Terraform.",
186-
))
187-
return nil, diags
188-
}
189178

190179
var err error
191180
opReq.ConfigLoader, err = c.initConfigLoader()

internal/command/views/json/policy.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type PolicyInfo struct {
2020
Snippet *DiagnosticSnippet `json:"snippet,omitempty"`
2121
}
2222

23+
// PolicyMetadata contains policy-specific metadata about a diagnostic.
2324
type PolicyMetadata struct {
2425
PolicySetName string `json:"policy_set_name,omitempty"`
2526
PolicySetPath string `json:"policy_set_path,omitempty"`
@@ -29,6 +30,7 @@ type PolicyMetadata struct {
2930
EnforceIndex *int32 `json:"enforce_index,omitempty"`
3031
}
3132

33+
// EnforceMetadata contains metadata about the enforcement block which the diagnostic is associated with.
3234
type EnforceMetadata struct {
3335
BlockIndex *int32 `json:"block_index,omitempty"`
3436
}

internal/command/views/view.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -158,31 +158,34 @@ func (v *View) PolicyResults(results *plans.PolicyResults) {
158158
foundInfo = true
159159
buf.WriteString("Policy Info:\n")
160160
if info.PolicyRange != nil && info.PolicySnippet != nil {
161-
buf.WriteString(fmt.Sprintf(
161+
fmt.Fprintf(
162+
&buf,
162163
"on %s line %d, in %s\n",
163164
info.PolicyRange.Filename,
164165
info.PolicyRange.Start.Line,
165166
info.PolicySnippet.Code,
166-
))
167+
)
167168
} else if enforcement.Policy != nil {
168-
buf.WriteString(fmt.Sprintf(
169+
fmt.Fprintf(
170+
&buf,
169171
"in policy %s\n",
170172
enforcement.Policy.Address,
171-
))
173+
)
172174
}
173-
buf.WriteString(fmt.Sprintf("%q\n", info.Message))
175+
fmt.Fprintf(&buf, "%q\n", info.Message)
174176

175177
if !result.ConfigDeclRange.Empty() {
176178
cfgRange := result.ConfigDeclRange
177179
resourceContext := string(cfgRange.SliceBytes(configSources[cfgRange.Filename]))
178180

179181
// Here we want the resource source context
180-
buf.WriteString(fmt.Sprintf(
182+
fmt.Fprintf(
183+
&buf,
181184
"\non %s line %d, in %s\n",
182185
cfgRange.Filename,
183186
cfgRange.Start.Line,
184187
resourceContext,
185-
))
188+
)
186189
}
187190
buf.WriteString("\n")
188191
}

internal/terraform/context_apply.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ type ApplyOpts struct {
4949
// the actual root modules.
5050
AllowRootEphemeralOutputs bool
5151

52-
// Locks is a read-only snapshot of provider locks (from the dependency lock
52+
// ProviderLocks is a read-only snapshot of provider locks (from the dependency lock
5353
// file). This is required by policy evaluations against providers to access version information.
54-
Locks map[addrs.Provider]*depsfile.ProviderLock
54+
ProviderLocks map[addrs.Provider]*depsfile.ProviderLock
5555

5656
// Optional policy client.
5757
// When set, policy evaluation logic will be executed in the graph.
@@ -73,7 +73,7 @@ func (po *PlanOpts) ApplyOpts() *ApplyOpts {
7373
return &ApplyOpts{
7474
ExternalProviders: po.ExternalProviders,
7575
AllowRootEphemeralOutputs: po.AllowRootEphemeralOutputs,
76-
Locks: po.Locks,
76+
ProviderLocks: po.ProviderLocks,
7777
}
7878
}
7979

@@ -221,7 +221,7 @@ func (c *Context) ApplyAndEval(plan *plans.Plan, config *configs.Config, opts *A
221221

222222
FunctionResults: lang.NewFunctionResultsTable(plan.FunctionResults),
223223

224-
Locks: opts.Locks,
224+
ProviderLocks: opts.ProviderLocks,
225225
PolicyClient: opts.PolicyClient,
226226
PolicyResults: opts.PolicyResults,
227227
})

0 commit comments

Comments
 (0)