Terraform "Forces Replacement" on Every Apply: Why aws_instance Gets Recreated (most_recent AMIs, security_groups, user_data) and How to Stop It Safely

Logeshwaran
—

When Terraform says "forces replacement" on an aws_instance you did not change, it is telling you that one argument it compares differs between your configuration and the real instance, and that the AWS provider cannot change that argument in place, so the only way to make them match is to destroy the instance and create a new one. In the plan you see -/+ next to the resource and # forces replacement next to the culprit line. On EC2 the usual culprits are an AMI data source with most_recent = true (every new image release changes the ID), security_groups used in a VPC instead of vpc_security_group_ids, a changed key_name, subnet_id or availability_zone, and user_data with user_data_replace_on_change = true. The surprise for most people: the configuration did not change at all; AWS published a new AMI, and your next terraform apply would quietly terminate a running server and its local data to "fix" it. The fix is to read the marked line, then either pin the value, switch to the in-place argument, or tell Terraform to stop comparing it with lifecycle { ignore_changes = [ami] }. This page shows each cause with the plan output, the fix, and the safety settings that stop a surprise replacement for good.

Jake's booking site ran on one EC2 instance built with Terraform, and Ethan only touched the code to add a tag. The plan said Plan: 1 to add, 0 to change, 1 to destroy. for a tag change. "Adding a label means deleting the server?" Jake asked. "Adding a label means Terraform noticed something else," Ethan said, and scrolled up to the line that ended in # forces replacement: the AMI. Amazon had published a new Amazon Linux image the day before, and his data source always picked the newest one. This page is that line, what it means, and the four lines Ethan added so it can never surprise him again.

⚡ Quick Answer

• Find the cause: the line marked # forces replacement in the plan, usually ami. Read the plan.

• New AMI every run: pin the AMI ID, or add ignore_changes = [ami]. AMI fix.

• Security groups: in a VPC use vpc_security_group_ids, never security_groups. Security group fix.

• Protect the server: prevent_destroy = true makes any plan that would replace it fail. Safety settings.

• Replace on purpose: terraform apply -replace=aws_instance.web. Deliberate replacement.

Arguments that force replacement · user_data · EBS volumes · create_before_destroy · Troubleshooting.

New to Terraform on AWS? Terraform keeps a state file that records what it created, compares it with your configuration and with what really exists in AWS, and the plan lists the actions needed to make reality match the code. Each argument of a resource is either updatable in place (a tag, an instance type with a stop and start) or "ForceNew", meaning AWS cannot change it on an existing resource, so Terraform must replace the whole thing. Our EC2 explainer and AMI explainer cover the AWS side.

🧭 NEW HERE? READ THESE FIRST

New to EC2, AMIs or Terraform with AWS? These five pages cover the basics this fix builds on:

💡 Never run terraform apply -auto-approve on a plan you have not read when it says "to destroy".

Read the plan: where "forces replacement" tells you the cause

A replacement in the plan looks like this. The symbol before the resource and the comment after one argument are the two things to find:

  # aws_instance.web must be replaced
-/+ resource "aws_instance" "web" {
      ~ ami                          = "ami-0a1b2c3d4e5f60001" -> "ami-0a1b2c3d4e5f60002" # forces replacement
      ~ id                           = "i-0123456789abcdef0" -> (known after apply)
      ~ public_ip                    = "203.0.113.25" -> (known after apply)
      ~ tags                         = {
          + "Owner" = "jake"
            # (1 unchanged element hidden)
        }
        # (28 unchanged attributes hidden)
    }

Plan: 1 to add, 0 to change, 1 to destroy.
  • -/+ means destroy, then create the replacement. +/- means create the replacement first, then destroy the old one (with create_before_destroy).
  • # forces replacement marks the argument (or arguments) responsible. Everything else marked ~ could have been updated in place; they are dragged along by the replacement.
  • (known after apply) on id, public_ip and private_ip is your warning that the server's identity and addresses will change, which matters for DNS records, allow lists and anything pointing at the old IP.

The full set of symbols you will see in plans, so you can read any of them at a glance:

SymbolMeaningRisk
+CreateLow; costs start
~Update in placeUsually low; some updates restart the resource
-DestroyHigh; read why
-/+Destroy, then create a replacementHigh; downtime and data loss possible
+/-Create the replacement, then destroy the old oneMedium; new IDs and addresses
<=Read a data source during applyNone by itself; values may change things downstream

On a long plan, search for the marker: terraform plan -no-color | grep -n "forces replacement". For scripts, the JSON plan lists the exact attribute paths in replace_paths: terraform plan -out=tf.plan, then terraform show -json tf.plan | jq '.resource_changes[] | select(.change.actions == ["delete","create"] or .change.actions == ["create","delete"]) | {address, replace_paths: .change.replace_paths}'.

What to do the moment your plan says "to destroy"

When you see a non-zero "to destroy" you did not expect, stop and work through this before you type yes:

  1. Do not apply. If you are in a pipeline, cancel the run. A plan only describes; nothing has happened yet.
  2. Find every resource marked "must be replaced" and, for each, the argument marked # forces replacement.
  3. Ask where the new value came from. Your edit, a data source (newest AMI, a list that reordered), a module upgrade, a provider upgrade, or someone changing the resource in the console.
  4. Decide whether you want the replacement. If yes, schedule it and back up data first. If no, fix the cause (pin it, correct the argument) or add it to ignore_changes.
  5. Plan again until "to destroy" shows only what you intend, ideally 0.
  6. Add protection to anything you would not want to lose: prevent_destroy, termination protection, and a CI check on destroy counts.

Write down what you found, even in one line in the pull request: "replacement caused by new AMI; added ignore_changes". The next person who sees the same plan will thank you. This takes you five minutes. Skipping it can cost you a server, its local data and its IP address, which is why many teams make step 1 automatic: a pipeline that stops and asks a person whenever the destroy count is not zero.

Cause 1: the AMI changed, because "most_recent" found a newer one

This is the most common reason an instance is replaced on a run where nobody touched it. The configuration usually looks like this:

data "aws_ami" "al2023" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["al2023-ami-2023.*-x86_64"]
  }
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.al2023.id
  instance_type = "t3.small"
}

Every time AWS publishes a new image matching the filter, the data source returns a new ID, and because ami cannot be changed on a running instance, Terraform plans a replacement. The same happens with aws_ssm_parameter lookups of the "latest AMI" public parameters, such as /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64, which AWS updates every time a new Amazon Linux 2023 image ships. Those parameters are a great way to find the current image; they are a poor thing to wire straight into a long-lived instance without one of the fixes below. Pick one of three fixes:

  1. Ignore AMI drift on the existing instance (most common for long-lived servers). The instance keeps its original image; new instances still get the newest one:
    resource "aws_instance" "web" {
      ami           = data.aws_ami.al2023.id
      instance_type = "t3.small"
    
      lifecycle {
        ignore_changes = [ami]
      }
    }
  2. Pin the AMI ID in a variable (ami = var.web_ami) and change it deliberately when you want to roll to a new image, as a reviewed change with a planned replacement.
  3. Accept replacement as the design for stateless servers behind a load balancer, and let an Auto Scaling group with a launch template roll new images out gradually instead of a single aws_instance being destroyed.

Option 1 has a cost worth naming: the instance never gets a newer image, so patching becomes the operating system's job (dnf update, Systems Manager Patch Manager) rather than Terraform's. That is how most long-lived servers are patched anyway.

The aws_instance arguments that force replacement

Not every argument is equal. These top-level aws_instance arguments are marked ForceNew in the AWS provider: change any of them, in code or by drift, and the instance is replaced:

ArgumentWhy it changes unexpectedlyUsual fix
amimost_recent data source or SSM "latest" parameterPin, or ignore_changes = [ami]
security_groupsNames used in a VPC, which the API reports differentlyUse vpc_security_group_ids
subnet_id, availability_zoneA subnet chosen by an index or a list that reorderedReference a specific subnet by ID or tag
key_nameA new key pair, or a key pair resource recreatedKeep the original key; manage access with SSM
private_ipA hard-coded IP edited, or computed differentlyLeave it unset, or never change it
associate_public_ip_addressSet explicitly when the subnet's default differsSet it to match, or use an Elastic IP
tenancy, placement_group, host_id, ebs_optimized, hibernationRarely changed by accident; usually deliberate editsPlan the replacement
launch_template (ID or name)Switching to a different templateChange versions, not templates

Inside root_block_device and ebs_block_device, changing encrypted or kms_key_id also requires replacement, and so do several network interface settings. By contrast, instance_type, user_data (by default), tags, vpc_security_group_ids, the IAM instance profile and monitoring settings change in place, some with a stop and start.

Other AWS resources that commonly force replacement

EC2 instances are the famous case, but you will meet the same message on other resources. These arguments force replacement in the AWS provider, and they are the ones you are most likely to edit casually:

ResourceArguments that force replacementWhat replacement costs you
aws_security_groupname, description, vpc_idA new group ID; replacement can hang while instances still use the old group
aws_s3_bucketbucket (the name)A new, empty bucket; the old one cannot be deleted while it holds objects
aws_iam_rolename, pathA new role ARN; trust policies and resource policies naming the old ARN stop working
aws_lbname, internal, load_balancer_typeA new DNS name; every CNAME and alias must move
aws_db_instanceengine, db_name, availability_zone, storage_encrypted, kms_key_idA new, empty database unless you restore from a snapshot
aws_lambda_functionpackage_type (Zip to Image)A new function version history; triggers re-created

Two counterexamples are useful to know: renaming an RDS instance's identifier is done in place by the provider (the endpoint name changes, the data stays), and changing an IAM role's max_session_duration or policies never replaces the role. For databases, the safest habit is the same as for servers: prevent_destroy = true and deletion protection on, so a replacement can only happen when you remove both on purpose.

Cause 2: security_groups in a VPC

The security_groups argument takes security group names and is meant for the default VPC (and the long-retired EC2-Classic). In any other VPC, the API reports the instance's groups by ID, Terraform compares names against what it reads back, sees a difference, and because security_groups is ForceNew, plans a replacement on every run:

# before: replaced on every apply in a custom VPC
resource "aws_instance" "web" {
  subnet_id       = aws_subnet.private_a.id
  security_groups = [aws_security_group.web.name]
}

# after: updated in place, never replaced
resource "aws_instance" "web" {
  subnet_id              = aws_subnet.private_a.id
  vpc_security_group_ids = [aws_security_group.web.id]
}

Switching from one to the other is itself a change Terraform compares, so on the first plan after the edit you may still see a replacement for the old argument. To switch without losing the instance, add security_groups to ignore_changes for one apply, or remove the instance from state and import it again with the new configuration (both shown below).

Cause 3: user_data and user_data_replace_on_change

By default, changing user_data on an existing instance does not replace it: the provider stops the instance, updates the user data and starts it again. Replacement happens only if you set user_data_replace_on_change = true, which some teams do on purpose so new user data always runs on a fresh instance (user data scripts normally run only at first boot, so a changed script on an old instance does nothing until something re-runs it; our user data guide explains why).

The trap is user data that changes on every run without anyone editing it: a templatefile() that includes a timestamp, a random value, a password from a resource that regenerates, or content that differs between machines (Windows line endings from one laptop, Unix from another). With user_data_replace_on_change = true, each of those is a replacement; without it, each is a stop and start, which is also an outage. Keep user data deterministic: pass changing values through Systems Manager Parameter Store or tags that the instance reads at boot, not through the script itself.

EBS volume settings that replace the instance

Block device settings inside the instance resource are a quieter source of replacements. Changing encrypted or kms_key_id on the root_block_device requires a new instance, because an existing volume cannot be encrypted in place. Changes to inline ebs_block_device blocks are also handled as part of the instance and can force replacement. Two habits avoid this:

  • Manage data volumes as separate aws_ebs_volume and aws_volume_attachment resources, so volume changes never touch the instance and volumes survive an instance replacement.
  • Turn on EBS encryption by default for the account and Region (aws_ebs_encryption_by_default), so new volumes are encrypted without anyone setting it per instance.

Growing a volume (volume_size on the root device) is updated in place by the provider, then you extend the file system inside the instance; our grow EBS guide covers the second half. Remember too that an instance replacement deletes root volumes and any volume with delete_on_termination = true, so data on them is gone unless you snapshotted it; EBS volumes attached separately are kept.

count index shifts: replacing the wrong instances

A different kind of surprise replacement comes from count. Instances created from a list are tracked by position, as index 0, 1 and 2 of aws_instance.app. Remove the first item from the list and every later item moves up one position, so Terraform sees that instance 0 now has instance 1's settings and plans to change or replace them all:

# fragile: removing "api" from the front shifts "worker" and "cron" down one index
variable "apps" { default = ["api", "worker", "cron"] }

resource "aws_instance" "app" {
  count         = length(var.apps)
  ami           = var.ami
  instance_type = "t3.small"
  subnet_id     = var.subnet_ids[count.index]
  tags          = { Name = var.apps[count.index] }
}

# stable: each instance is keyed by its name, so removing one touches only that one
resource "aws_instance" "app" {
  for_each      = { api = var.subnet_a, worker = var.subnet_b, cron = var.subnet_a }
  ami           = var.ami
  instance_type = "t3.small"
  subnet_id     = each.value
  tags          = { Name = each.key }
}

Because subnet_id forces replacement, the shifted list in the first version can replace instances you never meant to touch. With for_each and meaningful keys, you remove api and only aws_instance.app["api"] is destroyed. If you already have a count resource, moved blocks can map each old index to a new key so the switch itself replaces nothing.

Provider and module upgrades that suddenly replace things

If a plan starts replacing resources right after terraform init -upgrade, the cause is often a new provider or module version that changed a default, renamed an argument, or started reading a value differently. A few habits keep upgrades from surprising you:

  • Pin versions with constraints such as version = "~> 6.0" for providers and exact versions for modules, and commit the .terraform.lock.hcl file so everyone uses the same provider build.
  • Upgrade on purpose, in a branch: run terraform init -upgrade and terraform plan, read the upgrade guide or changelog for anything marked as a breaking change, and only merge when the plan is clean or every change is understood.
  • Upgrade one thing at a time: a provider bump and a module bump in the same change make it hard to know which caused a replacement.

Major provider versions deserve extra care, because they are where defaults and argument names are allowed to change. Read the provider's upgrade guide for the new major version from top to bottom before you run the plan, search it for the resource types you use, and expect to adjust a few arguments. A clean plan after a major upgrade is something you earn, not something you assume.

Keep the IP address even if the instance is replaced

One reason replacements hurt is that the public IP changes, and with it DNS records, firewall allow lists and anything a customer bookmarked. An Elastic IP keeps the address stable: Terraform associates it with whatever instance is current, so after a replacement the same address points at the new server:

resource "aws_eip" "web" {
  domain = "vpc"
  lifecycle { prevent_destroy = true }
}

resource "aws_eip_association" "web" {
  instance_id   = aws_instance.web.id
  allocation_id = aws_eip.web.id
}

Keeping the Elastic IP in its own resource, protected with prevent_destroy, means even a planned replacement of the instance keeps your address. Public IPv4 addresses, including Elastic IPs, are billed by the hour, so use one only where a stable address matters; behind a load balancer you point DNS at the load balancer instead and do not need it.

ignore_changes: what it does and when it is the right fix

ignore_changes tells Terraform to stop comparing specific arguments after the resource exists. The configuration's value is used at creation; after that, differences in those arguments are not planned. Use it for arguments that something else legitimately changes, or that you do not want to drive replacements:

lifecycle {
  ignore_changes = [
    ami,                       # keep the image the instance was built from
    user_data,                 # bootstrap script only matters at first boot
    tags["LastPatched"],       # set by a patching job, not by Terraform
  ]
}

Rules worth knowing: the list contains attribute names, not strings in quotes; you can name map keys like tags["LastPatched"]; ignore_changes = all ignores every argument (rarely wise, because then Terraform cannot fix anything on that resource); and lifecycle settings accept only literal values, not variables, because Terraform reads them before it evaluates expressions. ignore_changes is the right tool when the drift is expected. When the drift is a mistake, such as security_groups in a VPC, fix the argument instead of hiding it.

Safety settings that stop surprise replacements

For servers that must never be replaced by accident, add a guard rail so a bad plan fails loudly instead of applying:

resource "aws_instance" "web" {
  ami                     = data.aws_ami.al2023.id
  instance_type           = "t3.small"
  vpc_security_group_ids  = [aws_security_group.web.id]
  disable_api_termination = true

  lifecycle {
    prevent_destroy = true
    ignore_changes  = [ami]
  }
}
  • prevent_destroy = true: any plan that would destroy this resource, including a replacement, is an error. You must remove the setting (a visible, reviewed change) before the instance can be replaced or deleted.
  • disable_api_termination = true: EC2 termination protection, which also stops termination from the console or the CLI. Terraform must turn it off before it can replace the instance, which adds a second deliberate step.
  • Review plans in CI: fail the pipeline if a plan contains a delete for protected resource types, or require a human approval whenever "to destroy" is not zero.

These are the four lines Ethan added for Jake's server: vpc_security_group_ids, termination protection, prevent_destroy and ignore_changes = [ami]. "So now it can never be deleted?" Jake asked. "Now it can only be deleted on purpose," Ethan said.

Replacing an instance on purpose: -replace instead of taint

Sometimes you do want a fresh instance, for example after a broken update or to pick up a new AMI you pinned. Use the -replace option, which plans a replacement for exactly one resource without editing code:

terraform plan  -replace=aws_instance.web
terraform apply -replace=aws_instance.web

# several at once, or single instances of a for_each resource (count instances take a number in brackets)
terraform apply -replace='aws_instance.web["blue"]' -replace='aws_instance.web["green"]'

-replace replaced the older terraform taint command in Terraform v0.15.2 and later; it shows the replacement in the plan for review instead of silently marking state. It cannot be combined with -destroy, and it does nothing on a resource with prevent_destroy = true except fail, by design.

replace_triggered_by: replace one resource when another changes

The opposite problem, a resource that should be replaced when something else changes but is not, has its own setting. replace_triggered_by replaces a resource whenever a referenced resource or attribute changes:

resource "terraform_data" "app_version" {
  input = var.app_version
}

resource "aws_instance" "worker" {
  ami           = var.worker_ami
  instance_type = "t3.small"

  lifecycle {
    replace_triggered_by = [terraform_data.app_version]
  }
}

It accepts only references to managed resources (or their attributes), not plain variables, which is why the example wraps the version in a terraform_data resource. Use it sparingly: every trigger is another way for an apply to replace something.

create_before_destroy: replace without a gap

When a replacement is unavoidable, create_before_destroy = true creates the new instance first and destroys the old one after, so the plan shows +/- instead of -/+. That shortens the outage, but on a single instance it does not remove it: the new instance has a new ID and new IPs, DNS records or Elastic IP associations must move, and anything with a fixed name or address (a private_ip, a name tag used for lookups) can collide while both exist. Two more details: if a resource with create_before_destroy depends on another, Terraform turns it on for the dependency too, and destroy-time provisioners do not run for resources that use it.

For anything that must stay up through replacements, the real answer is more than one instance: an Auto Scaling group behind a load balancer, where new instances are started and checked before old ones are stopped. Terraform then manages the launch template, and image changes roll out as an instance refresh rather than a destroy.

Why the provider cannot "just change" these arguments

It can feel like Terraform is being lazy, but the limit comes from AWS. An EC2 instance's image is the disk it booted from; there is no API to swap the boot image of a running instance. Its subnet decides its network interface and Availability Zone, which are fixed at launch. Its key pair is written into the instance once, at first boot. A security group's name and description cannot be edited after creation in the EC2 API, and a bucket's name is its global identity. When the AWS API has no "modify" call for a property, the provider has only one way to make reality match your code: build a new resource. Knowing this turns the plan's message into a design question: should this value ever change for this resource? If the answer is no, protect it; if yes, design for replacement.

Catch unexpected replacements in CI before anyone applies

You can make "nobody notices the destroy line" impossible with a small check in your pipeline. Save the plan, then fail the job if any resource would be deleted, unless a person has approved it:

terraform plan -out=tf.plan -input=false
terraform show -json tf.plan > plan.json

DESTROYS=$(jq '[.resource_changes[] | select(.change.actions | index("delete"))] | length' plan.json)
if [ "$DESTROYS" -gt 0 ]; then
  echo "This plan deletes or replaces $DESTROYS resource(s):"
  jq -r '.resource_changes[] | select(.change.actions | index("delete")) | "\(.address)  replace_paths=\(.change.replace_paths // [] | tostring)"' plan.json
  exit 1
fi

Run this before the apply step, and give your team a separate, approved path for plans that are meant to replace things. The printed replace_paths tell the reviewer exactly which argument caused each replacement, so the conversation starts at the cause instead of at "why is it deleting the server?".

When someone changed the resource in the console

Drift from manual changes behaves differently depending on the argument. If someone added a security group in the console, your next plan shows an in-place update that puts the groups back to what your code says. If someone changed something that is ForceNew in Terraform, the plan shows a replacement to undo it, which is almost never what you want. Run terraform plan -refresh-only to see what changed outside Terraform without proposing fixes, then decide: copy the change into your code (so the next plan shows nothing), revert it by hand in the console, or accept Terraform's update. Treat a console change to a ForceNew argument as an incident: put the value back, and talk with whoever made it about using code next time.

Design for replacement: launch templates and Auto Scaling

The lasting cure for replacement anxiety is to make replacement boring. Instead of one long-lived aws_instance, run your app from an aws_launch_template and an aws_autoscaling_group of one or more instances behind a load balancer. A new AMI then becomes a new launch template version, and an instance refresh replaces instances one at a time, waiting for each new one to pass health checks before the next old one goes. Nothing important lives on the instances: data sits in RDS, S3 or separate EBS or EFS volumes, configuration comes from Parameter Store, and logs go to CloudWatch. You still read the plan, but "1 to destroy" on an instance stops being frightening, because the group was designed to lose instances.

For Jake's single server, Ethan went with protection rather than redesign, which is the right call for a small, quiet workload. When the shop opens a second location, the booking app moves behind an Auto Scaling group and the AMI goes back to "newest".

Before a planned replacement: protect the data

When you decide a replacement is right, take two minutes to make sure nothing is lost with the old instance:

  • Make an image of the old instance: aws ec2 create-image --instance-id i-0123456789abcdef0 --name "web-before-replace-2026-10-22" --no-reboot. It captures every attached EBS volume as snapshots, so you can launch the old server again if the new one misbehaves. (--no-reboot is convenient but may capture files mid-write; stop the app first if you can.)
  • Copy anything on instance store volumes, which never survive a stop or termination (our EBS vs instance store guide explains the difference).
  • Check delete_on_termination on attached volumes; volumes with true are deleted with the instance.
  • Lower DNS TTLs a day ahead if records point at the instance's IP, so clients follow the new address quickly, or use an Elastic IP as shown above.

Delete the safety image a week or two later, once you are sure you will not need it; its snapshots are billed for as long as they exist.

A safe aws_instance block, all together

Putting the fixes on this page together, this is a long-lived single server that will not be replaced by surprise, keeps its address and data, and still lets you replace it deliberately:

resource "aws_instance" "web" {
  ami                     = data.aws_ami.al2023.id
  instance_type           = "t3.small"
  subnet_id               = aws_subnet.public_a.id
  vpc_security_group_ids  = [aws_security_group.web.id]
  iam_instance_profile    = aws_iam_instance_profile.web.name
  disable_api_termination = true
  user_data               = file("${path.module}/bootstrap.sh")   # deterministic, no timestamps

  root_block_device {
    volume_size = 20
    encrypted   = true
  }

  lifecycle {
    prevent_destroy = true
    ignore_changes  = [ami, user_data]
  }
}

With this block, a new AMI, a tweak to the bootstrap script or a tag change never replaces the server; changing the instance type stops and starts it; and replacing it requires removing prevent_destroy and termination protection, two deliberate, reviewable steps. Pair it with the Elastic IP block and a separate aws_ebs_volume for data, and the worst a surprise plan can do is fail.

The same rules in OpenTofu

If you use OpenTofu instead of Terraform, everything on this page applies unchanged: the plan output, the # forces replacement marker, -replace, lifecycle settings, moved and import blocks all work the same way, with tofu in place of terraform on the command line. The AWS provider is the same provider, so the arguments that force replacement are the same too. If you are moving a project from Terraform to OpenTofu, the first tofu plan against the existing state should show no changes at all; if it shows replacements, the provider version differs from the one your lock file recorded, so match the version before applying anything. The CI check above works unchanged with tofu show -json.

The same idea in CloudFormation: "Replacement: True"

If your team also uses CloudFormation, the concept is identical under a different name. Each resource property in the CloudFormation documentation is marked with its update requirement: "No interruption", "Some interruptions" or "Replacement". A change set shows a Replacement column for every modified resource, with True, False or Conditional. Reading that column before executing a change set is the CloudFormation version of finding # forces replacement in a plan, and the protections map across too: DeletionPolicy: Retain and UpdateReplacePolicy: Retain keep the old resource when one is replaced or deleted, and stack policies can deny updates that would replace protected resources. Whatever tool you use, the habit is the same: look for the replacement marker before you approve, every time.

Fix the configuration without losing the instance: state rm and import

Sometimes the cleanest fix (renaming a resource, moving it into a module, switching security_groups to vpc_security_group_ids) would show a replacement even though the real instance is fine. Terraform has tools that change what it tracks without touching AWS:

  • Renaming or moving: add a moved block, moved { from = aws_instance.web to = module.web.aws_instance.this }, and the plan shows a move instead of a destroy and create.
  • Re-adopting an instance with new settings: terraform state rm aws_instance.web (Terraform forgets it; the instance keeps running), update the configuration to match the real instance, then bring it back with an import block, import { to = aws_instance.web id = "i-0123456789abcdef0" }, and plan until it shows no changes.

Run terraform plan after each step and only apply when it shows 0 to destroy. Back up the state first (with an S3 backend, versioning on the bucket gives you that for free; our S3 backend guide covers setting it up).

"Forces replacement" troubleshooting, by symptom

The instance is replaced on every apply with no code change

An argument changes on its own: a most_recent AMI, security_groups in a VPC, or non-deterministic user_data with replace on change. Find the marked line and pin, fix or ignore it.

Changing a tag plans a replacement

The tag is not the cause; another argument drifted at the same time. Look for the line ending in # forces replacement.

ignore_changes does not stop the replacement

The forcing argument is a different one, or it is inside a block (such as root_block_device) you did not list. Check replace_paths in the JSON plan and ignore that path.

"Instance cannot be destroyed" because of prevent_destroy

The protection worked. If the replacement is really wanted, remove prevent_destroy in a reviewed change, then apply; otherwise fix the cause of the replacement.

Replacement fails with termination protection errors

disable_api_termination is on. Set it to false and apply, then run the replacement, or leave it on if the replacement was a surprise.

The new instance cannot start because the private IP is in use

A fixed private_ip with create_before_destroy: both instances want the same address. Remove the fixed IP or replace with destroy first.

subnet_id changes between runs

The subnet is chosen by index from a list that changed order (a data source or a new subnet). Select the subnet by ID or a specific tag.

The plan replaces an instance after a provider upgrade

A new provider version changed a default or how an argument is read. Read the upgrade guide, pin the previous version to confirm, then adjust the configuration so the plan is clean before upgrading again.

Removing one item from a list replaces several instances

The resource uses count, so indexes shifted. Switch to for_each with stable keys, using moved blocks to map the old indexes.

A security group replacement hangs for a long time

The old group is still attached to instances or network interfaces, so it cannot be deleted. Use name_prefix with create_before_destroy so the new group exists first, or move the instances to the new group before the old one is removed.

key_name forces replacement after rotating a key

Key pairs are set at launch. Keep the original key name in Terraform, and manage access with Systems Manager Session Manager or by updating authorized_keys on the instance.

Terraform "forces replacement": frequently asked questions

What does "forces replacement" mean in Terraform?

The marked argument cannot be changed on the existing resource, so Terraform must destroy it and create a new one to match the configuration. The plan shows -/+ for that resource.

Why does Terraform want to replace my EC2 instance every time?

Usually an AMI data source with most_recent = true picks up new images, or security_groups is used in a VPC. Pin the AMI or ignore it, and use vpc_security_group_ids.

How do I stop Terraform from replacing an instance when the AMI changes?

Add lifecycle { ignore_changes = [ami] } to the aws_instance, or pin the AMI ID in a variable and change it deliberately.

What is the difference between security_groups and vpc_security_group_ids?

security_groups takes names and is for the default VPC; changing it forces replacement. vpc_security_group_ids takes IDs, works in any VPC and updates in place.

Does changing user_data replace an EC2 instance in Terraform?

Not by default: the instance is stopped, updated and started. It is replaced only when user_data_replace_on_change is true.

What does -/+ mean in a Terraform plan?

Destroy the existing resource and then create a replacement. +/- means create the replacement first, then destroy the old one.

How do I force Terraform to recreate a resource?

Run terraform apply -replace=ADDRESS, for example -replace=aws_instance.web. It replaces terraform taint from v0.15.2 onward.

What does prevent_destroy do in Terraform?

It makes any plan that would destroy the resource, including a replacement, fail with an error until you remove the setting.

Can I use variables in ignore_changes?

No. Lifecycle settings accept only literal attribute names, because Terraform reads them before evaluating expressions.

What is replace_triggered_by in Terraform?

A lifecycle setting that replaces a resource whenever a referenced resource or attribute changes. It accepts only resource references, so wrap variables in terraform_data.

Which aws_instance arguments force replacement?

Among others: ami, security_groups, subnet_id, availability_zone, key_name, private_ip, associate_public_ip_address, tenancy, placement_group and ebs_optimized, plus encryption settings of the root volume.

Does create_before_destroy avoid downtime for a single instance?

It shortens it but does not remove it: the new instance has a new ID and IPs that DNS and clients must follow. Use an Auto Scaling group behind a load balancer for zero downtime.

Will I lose data when Terraform replaces an instance?

Yes, on the root volume and any volume deleted on termination. Separate aws_ebs_volume resources and snapshots keep data safe.

How do I see exactly why Terraform plans a replacement?

Look for # forces replacement in the plan, or read replace_paths in terraform show -json for the saved plan.

How do I rename a Terraform resource without replacing it?

Add a moved block from the old address to the new one. The plan then shows a move instead of destroy and create.

Is terraform taint deprecated?

It is superseded by the -replace option on plan and apply, which shows the replacement in the plan instead of changing state directly.

For readers preparing for an AWS certification

We have been covering AWS certifications alongside our fixes, so here is a short extra for readers studying for one. If you only came for the fix, you already have it; feel free to skip this part.

Exams that test this topic: DevOps Engineer – Professional (DOP-C02) • CloudOps Engineer – Associate (SOA-C03) • Solutions Architect – Associate (SAA-C03).

Here are the exam-style questions this topic tends to raise, with the reasoning you need to answer them:

1. Every terraform apply replaces an EC2 instance although nobody changed its code. The AMI comes from a data source with most_recent = true. What is the fix?

Add lifecycle { ignore_changes = [ami] } to the instance, or pin the AMI ID and change it deliberately.

2. Which Terraform setting makes any plan that would destroy a critical resource fail?

lifecycle { prevent_destroy = true }.

3. An instance in a custom VPC is replaced on every apply because of its security groups. What should change?

Use vpc_security_group_ids with group IDs instead of security_groups with names.

4. How do you recreate a degraded instance with Terraform without editing the configuration?

terraform apply -replace=aws_instance.web, which replaces terraform taint.

5. A web tier must survive AMI updates without downtime. Which design avoids single-instance replacement?

An Auto Scaling group with a launch template behind a load balancer, rolling new AMIs with an instance refresh.

6. Besides Terraform settings, what stops an EC2 instance from being terminated by mistake?

EC2 termination protection (disable_api_termination = true).

Exam codes and dates change often. Our AWS certification changes page keeps track of what is current.

πŸ“š ALSO READ

Where to go next, from state locks to user data:

📌 Bookmark this; the table of arguments that force replacement is the part you will check again.

The next plan Ethan ran showed Plan: 0 to add, 1 to change, 0 to destroy., the tag and nothing else. A month later, when he wanted the new image, he removed the AMI from ignore_changes during a quiet Sunday hour, read the plan twice and replaced the server on purpose. Jake asked how he knew it was safe this time. "This time I asked for it," Ethan said.

📌 If you keep one line from this page

Find the line marked "# forces replacement", then pin or ignore the AMI, use vpc_security_group_ids in VPCs, keep user data deterministic, protect important servers with prevent_destroy and termination protection, and replace on purpose with -replace.

-/+ destroy then create · +/- create then destroy · -replace from v0.15.2 · lifecycle values must be literals.

Revision note. Written October 22, 2026, with Terraform's lifecycle and plan behavior and the AWS provider's aws_instance schema of that date. "Look before you leap," the proverb says; with Terraform, read the plan before you apply.

Related