Terraform state management
Why state exists
State maps each resource address to a real object's identifier and caches its attributes. Without it Terraform cannot tell whether to create or update. State also contains sensitive values in plaintext (including variables marked sensitive), so it must be treated as a secret.
Backends
Local state (terraform.tfstate) is the default and cannot be locked. Remote backends (S3 with a lock mechanism, azurerm, gcs, HCP Terraform) centralize state and provide locking so concurrent applies cannot race. Backend config lives in a terraform { backend "s3" {} } block; partial configuration can be supplied with -backend-config. Changing backends requires terraform init -migrate-state.
Commands worth memorizing
terraform state list/state show- inspect addresses and attributes.terraform state mv- re-address a resource without destroying it (refactoring).terraform state rm- forget an object; it keeps running in the cloud and is no longer managed.terraform import ADDR ID- attach an existing object to an address whose configuration already exists.terraform state pull/push- read or overwrite remote state manually.terraform force-unlock <ID>- clear a stale lock left by a crashed run.terraform workspace new/select- multiple state files from one configuration (not a substitute for separate accounts).
Traps
state rmis notdestroy; destroy is notstate rm.- Editing state by hand is fragile - prefer
state mvormovedblocks. - Workspaces share configuration and credentials; they do not isolate blast radius the way separate accounts do.
Rule of thumb
Rename → state mv or moved; adopt → import; stop managing without deleting → state rm.