State CLI and Safe Refactoring
Scenario: A resource block is renamed for clarity and Terraform proposes destroying the existing object and creating an identical replacement.
State subcommands inspect and exceptionally transform address mappings: list, show, mv, rm, pull, and push. Prefer declarative moved and removed blocks because they record migration intent in version control and work for every collaborator. Use state mv for controlled one-time migrations and back up first. state rm forgets an object without deleting it; it does not make the object disappear.
Analogy: Renaming a contact does not replace the person; a moved block updates the address book while preserving identity.
A worked configuration
moved {
from = fakecloud_server.web
to = fakecloud_server.api
}
# Exceptional equivalent:
# terraform state mv fakecloud_server.web fakecloud_server.api
Refactors should have a near-empty infrastructure plan after address moves. Test migrations on a state copy or non-production environment, coordinate version rollout, and never let old configuration run after a state schema migration.
Note: Treat the plan as a change contract: understand every create, update, replacement, and destroy before approving it.
Goal: Reinforce this lesson in the tf-moved-refactor Terraform lab. Open/labs/terraformand choose slugtf-moved-refactor; the lab runs real Terraform against the offline FakeCloud provider.