Terraform Tutorial — What Is Terraform State?
Terraform state is a JSON file that records the mapping between your configuration and the real infrastructure resources in the cloud.
Why State Exists
When you write:
resource "aws_s3_bucket" "main" {
bucket = "my-app-bucket"
}
And run terraform apply, Terraform creates the bucket. But how does Terraform know the bucket already exists on the next apply? The state file.
State answers three critical questions:
| Question | How State Answers It |
|---|---|
| What exists? | Lists every resource Terraform manages |
| What are the IDs? | Stores cloud resource IDs (ARN, instance ID, etc.) |
| What changed? | Compares state to config to compute the plan |
How State Works in the Workflow
terraform plan
1. Read configuration files (.tf)
2. Read state file (terraform.tfstate)
3. Query cloud APIs for current resource state
4. Compare all three → generate plan
terraform apply
1. Execute the plan
2. Update state file with new resource IDs/attributes
Default Location
By default, state is stored locally as terraform.tfstate in your project directory:
my-project/
├── main.tf
├── variables.tf
├── outputs.tf
├── terraform.tfstate ← state file
└── terraform.tfstate.backup ← previous state
Key Facts About State
| Fact | Detail |
|---|---|
| Format | JSON |
| Contains secrets | Yes — passwords, tokens stored in plaintext |
| Should be in Git? | Never — add to .gitignore |
| Can be shared? | Yes — use remote backends (S3, Terraform Cloud) |
| Can be corrupted? | Yes — never edit manually |
⚠️ Warning: The state file contains sensitive data in plaintext. Never commit it to version control. Always use a remote backend with encryption for team environments.
terraform.tfstate vs Reality
Terraform trusts the state file. If someone changes a resource manually (outside Terraform), the state becomes stale:
# Refresh state to match real infrastructure
$ terraform refresh
# Or use plan with refresh (default behavior)
$ terraform plan
terraform plan automatically refreshes state before computing changes.
What’s Next?
Let’s look inside the state file and understand its JSON structure.