Skip to content

replace-triggered-by must reference a valid resource or resource attribute #36802

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
5 changes: 5 additions & 0 deletions .changes/v1.12/BUG FIXES-20250331-170607.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
kind: BUG FIXES
body: replace-triggered-by must reference a valid resource or resource attribute
time: 2025-03-31T17:06:07.04296+02:00
custom:
Issue: "36740"
45 changes: 45 additions & 0 deletions internal/terraform/context_plan2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4399,6 +4399,51 @@ resource "test_object" "b" {
}
}

func TestContext2Plan_triggeredByInvalid(t *testing.T) {
m := testModuleInline(t, map[string]string{
"main.tf": `
resource "test_object" "a" {
count = 1
test_string = "new"
}
resource "test_object" "b" {
count = 1
test_string = test_object.a[count.index].test_string
lifecycle {
# reference to an invalid attribute "yikes" should cause an error
replace_triggered_by = [ test_object.a[count.index].yikes ]
}
}
`,
})

p := simpleMockProvider()

ctx := testContext2(t, &ContextOpts{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): testProviderFuncFixed(p),
},
})

state := states.BuildState(func(s *states.SyncState) {
s.SetResourceInstanceCurrent(
mustResourceInstanceAddr("test_object.a[0]"),
&states.ResourceInstanceObjectSrc{
AttrsJSON: []byte(`{"test_string":"old"}`),
Status: states.ObjectReady,
},
mustProviderConfig(`provider["registry.terraform.io/hashicorp/test"]`),
)
})

_, diags := ctx.Plan(m, state, &PlanOpts{
Mode: plans.NormalMode,
})
if !diags.HasErrors() {
t.Fatalf("expected errors, got none")
}
}

func TestContext2Plan_dataSchemaChange(t *testing.T) {
// We can't decode the prior state when a data source upgrades the schema
// in an incompatible way. Since prior state for data sources is purely
Expand Down
41 changes: 37 additions & 4 deletions internal/terraform/eval_context_builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,10 +407,7 @@ func (ctx *BuiltinEvalContext) EvaluateReplaceTriggeredBy(expr hcl.Expression, r
return nil, false, diags
}

path, _ := traversalToPath(ref.Remaining)
attrBefore, _ := path.Apply(change.Before)
attrAfter, _ := path.Apply(change.After)

attrBefore, attrAfter, diags := evalTriggeredByRefPath(ref, change)
if attrBefore == cty.NilVal || attrAfter == cty.NilVal {
replace := attrBefore != attrAfter
return ref, replace, diags
Expand All @@ -421,6 +418,42 @@ func (ctx *BuiltinEvalContext) EvaluateReplaceTriggeredBy(expr hcl.Expression, r
return ref, replace, diags
}

// evalTriggeredByRefPath evaluates the attribute reference path in the context of the
// resource change objects. It returns the before and after values of the attribute
// and any diagnostics that occurred during evaluation.
func evalTriggeredByRefPath(ref *addrs.Reference, change *plans.ResourceInstanceChange) (cty.Value, cty.Value, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
path, key := traversalToPath(ref.Remaining)

applyPath := func(value cty.Value) (cty.Value, tfdiags.Diagnostics) {
attr, err := path.Apply(value)
if err != nil {
return cty.NilVal, tfdiags.Diagnostics{}.Append(tfdiags.AttributeValue(
tfdiags.Error,
"Invalid attribute path",
fmt.Sprintf(
"The specified path %q could not be applied to the object specified in replace_triggered_by:\n"+
"Path: %s\n"+
"Error: %s\n"+
"Please check your configuration and ensure the path is valid.",
key, ref.DisplayString(), err.Error(),
),
path,
))
}
return attr, nil
}

// Apply the path to the "before" and "after" states
attrBefore, beforeDiags := applyPath(change.Before)
diags = diags.AppendWithoutDuplicates(beforeDiags...)

attrAfter, afterDiags := applyPath(change.After)
diags = diags.AppendWithoutDuplicates(afterDiags...)

return attrBefore, attrAfter, diags
}

func (ctx *BuiltinEvalContext) EvaluationScope(self addrs.Referenceable, source addrs.Referenceable, keyData InstanceKeyEvalData) *lang.Scope {
switch scope := ctx.scope.(type) {
case evalContextModuleInstance:
Expand Down