Lesson 9 / 25

Updates Versus Replacements

Some changes force a new resource.

forces replacement

Changing some arguments can be applied in place (~), but others cannot be changed on an existing resource, so the provider must destroy and re-create it; the plan marks those arguments # forces replacement. Examples in clouds: renaming a database instance, changing an availability zone, changing a disk type. Use create_before_destroy in a lifecycle block to create the replacement first, and plan migrations for stateful resources.

A change that forces replacement, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. Changing env from dev to staging changes the file name, which this resource cannot update in place, so the plan replaces it: 1 to add and 1 to destroy.

terraform plan -no-color -var env=staging | grep -E "must be replaced|forces replacement|Plan:"

Output:

  # local_file.config must be replaced
      ~ content              = <<-EOT # forces replacement
      ~ filename             = "./out/shop-dev.conf" -> "./out/shop-staging.conf" # forces replacement
Plan: 1 to add, 0 to change, 1 to destroy.

Use create_before_destroy for zero downtime

For resources that can coexist briefly (certificates, launch templates), set lifecycle { create_before_destroy = true }.

Quick check: What does "# forces replacement" mean next to an argument?

  • The argument is invalid
  • It will be updated in place
  • Changing it requires destroying and re-creating the resource
  • Terraform will ignore it
Answer

Changing it requires destroying and re-creating the resource — Read these before approving.