Terraform state, drift and a failed apply
What is Terraform state, how do you manage it in a team, and how do you handle drift or an apply that fails halfway?
TL;DR
State is Terraform's record of which real resources map to which resources in your code, plus their last-known attributes. plan compares your code, the state and reality to compute changes. In a team, keep state in a remote backend (S3, GCS, Terraform Cloud) with locking so two applies can't run at once, with versioning for recovery and encryption, since state often contains secrets. Drift is when reality changes outside Terraform (someone edits a resource in the console); plan shows it, and you either re-apply the code or update the code to match. A failed apply leaves partial changes, but state records what was created, so you fix the cause and run apply again.
Key points
- Never edit state by hand. Use
terraform state mv,state rm,import, ormoved {}andimport {}blocks for refactors. - Split state by environment and component (network, database, app) to shrink the blast radius and speed up plans.
- Detect drift on a schedule: run
terraform plan -detailed-exitcodein CI and alert on changes. - Prevent drift: read-only console access in production, with changes only through pipelines.
- Run
planin CI on every pull request, require approval, thenapplythe saved plan file. - A stuck lock after a crashed run:
terraform force-unlock <id>, only after confirming nothing else is running.
Example
terraform {
backend "s3" {
bucket = "acme-tf-state"
key = "prod/network/terraform.tfstate"
region = "eu-west-1"
encrypt = true
use_lockfile = true # S3-native locking (older setups use a DynamoDB table)
}
}Common follow-ups
- How do you bring an existing resource under Terraform?
terraform import, or animport {}block, then write matching code untilplanshows no changes. - Workspaces vs separate directories for environments? Separate directories (or Terragrunt) make differences explicit and safer; workspaces suit identical copies.
What interviewers look for
Tip
What state is for, remote backend with locking, drift detection, and a calm recovery from a partial apply.
- Red flag: local state files committed to Git, or
-lock=falseas a habit.