Lesson 5 of 9 · 24m
Reading Plans, Refactoring, and State Moves
Treat the plan as a change review artifact, use moved blocks deliberately, and avoid destructive surprises when refactoring.
A Terraform plan is not build output. It is the closest thing you get to a database migration review for infrastructure. Teams that skim plans learn the difference the first time a rename becomes destroy and create on a stateful resource.
Read the plan like a skeptical reviewer
terraform plan -out=tfplan
terraform show -no-color tfplanLook first for replacement, not change count. Lines with -/+ mean Terraform intends to destroy and recreate. For load balancers, DNS records, databases, queues, and IAM roles, replacement can mean downtime, lost messages, or broken trust relationships. Ask whether replacement is required by the provider API or merely caused by careless refactoring.
Renames are not automatically safe
If you change:
resource "aws_security_group" "web" {}to:
resource "aws_security_group" "service" {}Terraform sees one object vanish and another appear. Since Terraform 1.1, preserve identity explicitly:
moved {
from = aws_security_group.web
to = aws_security_group.service
}Commit the moved block with the refactor and leave it long enough for every environment to apply it. Removing it too early is fine technically after all states are updated, but keeping it for a release cycle protects stragglers.
State moves are surgery, not routine cleanup
terraform state mv aws_instance.old aws_instance.new
terraform state rm aws_iam_access_key.legacy
terraform import aws_s3_bucket.logs acme-log-archiveUse state mv when configuration structure changed but real infrastructure did not. Use state rm only when Terraform should stop managing something that continues to exist. Use import to bring existing infrastructure under management, then reconcile configuration until plan is clean. None of these operations belong in normal CI for application deployment.
Refactor in small, verifiable steps
A safe sequence is: copy state backup, move or add moved blocks, run plan, verify no unexpected replacement, apply, then clean up dead code. If you change behavior and identity in the same commit, the plan becomes impossible to reason about. Separate mechanical relocation from semantic modification.
Field notes
-targetis not a safety mechanism; it is a scalpel for exceptional situations and can leave dependencies inconsistent.terraform plan -detailed-exitcodeis useful in automation: 0 means no changes, 2 means changes present.- Never treat an empty plan after import as optional cleanup; it is the proof that configuration matches reality.
- Large refactors deserve a written rollback path before apply, not improvisation after a bad destroy.
Was this lesson helpful?