Why would a tool built to converge infrastructure on a desired state keep destroying and rebuilding the same resource on every apply, even when nobody touched the code? Because, from Terraform's point of view, the desired state really is different each time. Somewhere a value that feeds an immutable argument either changes between runs or cannot be known until apply. Terraform does exactly what it is told, and the plan output already names the argument responsible.

The argument here runs in one direction: perpetual replacement is not a Terraform bug to be suppressed but a moving value to be found. Suppress it with ignore_changes before you understand it, and you trade a noisy plan for silent drift.

The plan already says why

A resource that will be replaced is marked with -/+ for destroy then create, or +/- when create_before_destroy is set. Inside the block, Terraform prints # forces replacement next to each attribute that triggered it.

  # aws_instance.web[0] must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami = "ami-0a1b2c3d4e5f60718" -> "ami-0f9e8d7c6b5a40321" # forces replacement
      ~ id  = "i-0123456789abcdef0" -> (known after apply)
        # (28 unchanged attributes hidden)
    }

Plan: 4 to add, 0 to change, 4 to destroy.

In a long plan the annotation is easy to miss. The JSON plan has a dedicated field, replace_paths, listing the attribute paths that caused each replacement. Use it in CI to print only what matters.

terraform plan -out=tfplan
terraform show -json tfplan | jq -r '
  .resource_changes[]
  | select(.change.actions == ["delete","create"] or .change.actions == ["create","delete"])
  | "\(.address)  \(.change.replace_paths)"'

Keep the output of two runs side by side. If the same address and path appear on two consecutive runs with no code change, you have a replacement loop. If the path differs between runs, or appears once and disappears, it is more likely a one-off change such as a renamed resource, which a moved block solves, or genuine drift made by someone in the console. A loop and a one-off need different fixes, so two plans 24 hours apart are worth more than one plan read very carefully. The rest of the work is finding out why that path moves.

Values designed to change on every run

The most direct cause is a function that returns a new value each time it runs. timestamp() returns the current time, uuid() a fresh random UUID, bcrypt() a new salted hash. Put any of them into an argument that forces replacement, and replacement happens on every plan, by design.

The same pattern hides inside providers. A data "aws_ami" block with most_recent = true returns whatever image is newest when the plan runs. Every time the image publisher releases an update, the AMI ID changes, and an aws_instance built from it is replaced. In the random provider, keepers decide when a random_password or random_id regenerates. Setting keepers = { rotate = timestamp() } means a new password on every apply, and every resource consuming it may follow.

terraform_data with triggers_replace, or the older null_resource with triggers, behaves the same way when fed a timestamp. Sometimes that is the intent, for example to rerun a provisioner on every deployment. Often it was copied from an example and forgotten.

The test is simple: search the configuration for timestamp(), uuid(), most_recent and keepers, and check whether any of them flows, directly or through locals and modules, into an attribute listed in replace_paths.

When the provider and the API disagree

The second family is quieter. The configuration says one thing, the cloud API stores a slightly different thing, and the provider compares them literally. If the attribute is one that forces a new resource, the result is a replacement every time.

Normalization is the usual culprit. An API may lowercase a name, reorder a list, strip trailing whitespace from a script, or canonicalize a JSON document. The provider reads the stored value during refresh, compares it with your configuration and sees a difference. Most providers suppress the well-known cases, but gaps exist, especially right after a new resource type or argument is introduced.

Some arguments are simply immutable in the API, and changing them must mean a new resource. On Google Cloud, metadata_startup_script on google_compute_instance forces replacement, while the same script placed under metadata with the key startup-script updates in place. A template that renders the script with a changing value, such as a build number, rebuilds the VM every apply under the first form and only updates metadata under the second.

To confirm this family, run terraform plan -refresh-only. It shows what Terraform read from the API without proposing changes to your configuration. If the refreshed value differs from what you wrote only in case, order or whitespace, change your configuration to match the API's canonical form.

Unknown values that leak into immutable arguments

A value does not have to change to cause replacement. It only has to be unknown at plan time. If a force-new argument receives a value shown as (known after apply), Terraform cannot prove it will be identical, so it plans a replacement.

The common source is a data source that cannot be read during planning. Since Terraform 0.13, a data source with depends_on pointing at a managed resource that has pending changes is deferred to the apply phase. Every attribute it returns becomes unknown, and anything downstream that forces replacement is replaced. Teams add depends_on to a data source to fix an ordering issue once, and from then on any change to the dependency triggers a rebuild of everything that reads it.

The same happens when a module output is computed from a resource that is itself being updated. The value may end up identical after apply, but during planning it is unknown.

The fix is to break the dependency: remove depends_on from data sources where the implicit reference is enough, pass stable inputs such as names or IDs from variables, and look for (known after apply) next to every # forces replacement line in the plan.

Index churn from count

Not every loop involves a single attribute. With count, resources are addressed by position: aws_instance.web[0], [1], [2]. If the list that drives count comes from a source whose order is not stable, such as a data source returning subnets or availability zones in an order the API does not guarantee, the element at index 0 may differ between runs. Terraform then sees index 0 changing its subnet, which forces replacement, and the same for every other index.

Even a stable list causes mass replacement when an element is removed from the middle. Remove the second of five entries and indexes 1 to 3 all shift, so three resources are rebuilt to delete one.

for_each with a map or set of strings addresses resources by key instead, so order no longer matters. Migrating from count to for_each requires moved blocks, or terraform state mv, to map old addresses to new keys without destroying anything. Done once, it removes this whole class of loop. When a list must stay, wrap it in sort() before using it, so the order at least becomes deterministic.

A worked example: four web servers rebuilt every night

An illustrative case. A team runs 4 aws_instance resources behind a load balancer, created with count = 4 from a data "aws_ami" lookup with most_recent = true. A CI job runs terraform apply -auto-approve every night at 02:00 to apply any merged changes.

Each instance takes about 90 seconds to launch and another 150 seconds to pass load balancer health checks, so 4 minutes per instance until it serves traffic. Without create_before_destroy, Terraform destroys first. With the default parallelism of 10, all 4 destroys run at once, then all 4 creates. The service has zero healthy targets for roughly 4 minutes.

The base image publisher releases a new AMI, say, 3 times in a given month. On those 3 nights the plan shows Plan: 4 to add, 0 to change, 4 to destroy, and the site is down for 12 minutes in total. The team notices only when a customer in a far time zone complains at 02:03 their time. The instances themselves cost the same afterwards, but the outage costs a support ticket and a trust problem.

The fix took three lines: pin the AMI ID as a variable updated by a deliberate pull request, add create_before_destroy = true so new instances come up before old ones go, and move the nightly job to plan only, with apply on merge. Replacement still happens, but only when someone chooses a new image, and without downtime.

Fixes that hold

Choose the fix by cause, not by habit, and confirm it with two clean plans in a row before closing the ticket.

For moving values, remove the moving source or pin it. Replace most_recent lookups with an explicit ID that changes through code review. Replace timestamp() in triggers with a value that changes only when you want a rerun, such as a hash of the file a provisioner uploads: filesha256("scripts/setup.sh").

For provider disagreements, write the canonical form the API returns, use the in-place variant of the argument where one exists, or upgrade to a provider version that suppresses the difference.

For unknown values, remove unnecessary depends_on on data sources and pass stable identifiers in.

Use ignore_changes only when an attribute is legitimately managed elsewhere, such as tags added by a cost tool or an image updated by an external pipeline:

resource "aws_instance" "web" {
  ami           = var.web_ami_id
  instance_type = "t3.small"

  lifecycle {
    create_before_destroy = true
    ignore_changes        = [tags["LastScannedBy"]]
  }
}

Every ignore_changes entry is a promise that someone else owns that value. Write down who.

Questions engineers ask about replacement loops

Is terraform apply -replace related to this problem? It is the opposite tool. -replace forces Terraform to replace one named resource on purpose, and it superseded the terraform taint command, which has been deprecated since version 0.15.2.

Can I use a variable inside ignore_changes? No. ignore_changes accepts only static references to attributes of the resource itself, or the keyword all. Expressions, variables and attributes of other resources are rejected when the configuration is validated.

Will prevent_destroy stop an unwanted replacement? Yes. If a resource with prevent_destroy = true would be destroyed, including as part of a replacement, the plan fails with an error instead of proceeding. It is a sensible guard on databases and storage buckets.

Why did replacements start right after a provider upgrade? New provider versions sometimes change defaults or how attributes are normalized. Read the changelog for the versions between the old and new constraint, and commit .terraform.lock.hcl so every runner uses the same provider build.

When not to stop the replacement at all: if your servers are built as immutable images and a new AMI is how security patches reach production, the replacement is the patching process, and ignore_changes = [ami] would freeze vulnerable machines in place. The same applies to resources whose replacement rotates credentials on purpose. In those cases keep the replacement and make it safe with create_before_destroy, health checks and a controlled apply, instead of making it disappear.