Terraform State (tfstate, remote state, locking)
Understand what Terraform state is, why it matters, and how remote state + locking improves safety.
Terraform state is the “source of truth” for what Terraform created.
Without state, Terraform can’t reliably know the mapping between your configuration and real-world resources.
Learning outcomes
You will learn:
- what
terraform.tfstatecontains - what happens when you lose state
- why remote state and locking are recommended
1) What Terraform state is
Terraform state typically stores:
- resource instance IDs
- provider metadata
- attributes needed to compute diffs
By default, Terraform writes state to a local file:
terraform.tfstate
It also creates a lock file for providers:
.terraform.lock.hcl
2) Inspecting state (safely)
You can view state contents:
terraform show
For a JSON view:
terraform show -json > state.json
Tip: treat state as sensitive—often it contains secrets (directly or via outputs).
3) The relationship: config vs state vs reality
- Configuration: your desired infrastructure (
.tffiles) - State: Terraform’s record of what it created
- Reality: actual infrastructure in the cloud
Terraform compares configuration + state to decide what to change in reality.
4) Common state pitfalls
Pitfall A: Deleting local state
If you delete terraform.tfstate, Terraform loses the history of what it created.
Consequences:
- Terraform may try to re-create resources
- You can end up with duplicates or destructive changes
Pitfall B: Sharing state unsafely
If multiple engineers use the same remote backend without locking, you risk concurrent applies.
5) Remote state + locking (recommended)
In real teams, remote backends are used (commonly S3, GCS, Azure Storage) with locking:
- S3 backend typically uses DynamoDB for locking
Example backend config (conceptual)
In Terraform, backend configuration is defined inside terraform {}.
terraform {
backend "s3" {
bucket = "my-terraform-state-bucket"
key = "envs/prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "my-terraform-locks"
encrypt = true
}
}
Note: In many setups, you must provide the backend config via CLI/workspace variables or re-run
terraform init.
6) Environments: separate state per environment
Common pattern:
devhas its own state filestaginghas its own state fileprodhas its own state file
Example keys:
envs/dev/terraform.tfstateenvs/staging/terraform.tfstateenvs/prod/terraform.tfstate
7) Cleanup reminder
When using remote state, terraform destroy can delete production resources if your config points at prod.
Always review terraform plan before applying/destroying.