How does Terraform state work?
· Category: DevOps & CI/CD
Short answer
Terraform state is a JSON file that maps resource definitions in your configuration to real-world resources. It is used to track metadata, dependencies, and resource attributes.
How it works
When you run terraform apply, Terraform refreshes the state by querying the provider APIs. It then compares the desired state with the current state and proposes changes. The state file is updated after a successful apply.
Example
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
}
}
Why it matters
State is required for Terraform to function. Without it, Terraform cannot track resource IDs or manage updates. Remote state with locking prevents conflicts when multiple people run Terraform.
Tips
- Never edit state files manually.
- Use
terraform statecommands for safe modifications. - Enable state versioning in your backend.
Common issues
- Local state is not suitable for teams.
- State file corruption requires restoration from backup.
- Sensitive values may be stored in plain text in state files.