Skip to content

Incorrect plan when using replace_triggered_by with -replace #37831

@g7r

Description

@g7r

Terraform Version

Terraform v1.13.4
on linux_amd64

Terraform Configuration Files

variable "t" {
  type = string
}

resource "terraform_data" "t" {
  count = 100
  input = var.t
}

resource "terraform_data" "r" {
  count = 100
  input = count.index
  lifecycle {
    replace_triggered_by = [terraform_data.t[count.index]]
  }
}

Debug Output

https://gist.githubusercontent.com/g7r/759be7835d33f6fbc38828f61fdff4f8/raw/03ab3123308cd4ef6f50ef65863923b374e2cc94/tftrace.log

Expected Behavior

Plan: 100 to add, 100 to change, 100 to destroy.

Actual Behavior

Plan: 16 to add, 97 to change, 16 to destroy.

The numbers vary every time.

Steps to Reproduce

  1. terraform init
  2. terraform apply -var t=a
  3. terraform plan -var t=b -replace 'terraform_data.r[0]' -replace 'terraform_data.r[1]' -replace 'terraform_data.r[2]'

Additional Context

b.ForceReplace slice obtained from command line arguments is being passed by reference to graph nodes: https://github.com/hashicorp/terraform/blob/v1.13.4/internal/terraform/graph_builder_plan.go#L308

The number of -replace arguments matters. If len(b.ForceReplace) == cap(b.ForceReplace), the bug doesn't reproduce.

It doesn't matter which addresses to use for -replace. E.g. you can replace 3rd action with:

  • terraform plan -var t=b -replace a.a -replace a.b -replace a.c
  • terraform plan -var t=b -replace a.a -replace a.a -replace a.a

The same slice is being concurrently modified: https://github.com/hashicorp/terraform/blob/v1.13.4/internal/terraform/node_resource_plan_instance.go#L572

I suggest making a copy of the slice at graph_builder_plan.go.

References

No response

Generative AI / LLM assisted development?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugconfirmeda Terraform Core team member has reproduced this issuecore

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions