You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Terraform uses a state file to map your configuration to real-world resources. Understanding state is essential for working with Terraform safely and effectively, especially in team environments.
The Terraform state file (terraform.tfstate) is a JSON file that records:
Your Configuration (.tf) State File (.tfstate) Real Infrastructure
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ aws_instance.web │ ←──→ │ id: i-0abc123 │ ←──→ │ EC2 Instance │
│ type: t3.micro │ │ type: t3.micro │ │ i-0abc123 │
└──────────────────┘ └──────────────────┘ └──────────────────┘
| Purpose | Description |
|---|---|
| Mapping | Links resource addresses to real-world resource IDs |
| Performance | Caches resource attributes to avoid querying every API on every plan |
| Dependencies | Tracks dependency order for correct creation and destruction |
| Drift detection | Compares state with real infrastructure to detect out-of-band changes |
By default, Terraform stores state locally in terraform.tfstate:
ls -la terraform.tfstate
# -rw-r--r-- 1 user staff 4096 terraform.tfstate
A backend defines where Terraform stores state. Remote backends solve the problems of local state:
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "project/terraform.tfstate"
region = "eu-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
terraform {
backend "azurerm" {
resource_group_name = "terraform-rg"
storage_account_name = "tfstate12345"
container_name = "tfstate"
key = "project.terraform.tfstate"
}
}
terraform {
backend "gcs" {
bucket = "my-terraform-state"
prefix = "project"
}
}
| Backend | Provider | Locking | Encryption |
|---|---|---|---|
| S3 + DynamoDB | AWS | Yes (DynamoDB) | Yes (SSE) |
| azurerm | Azure | Yes (blob lease) | Yes |
| gcs | GCP | Yes | Yes |
| consul | HashiCorp | Yes | Optional |
| Terraform Cloud | HashiCorp | Yes | Yes |
| pg | Any (PostgreSQL) | Yes | TLS |
State locking prevents concurrent operations from corrupting the state:
User A: terraform apply → Acquires lock → Applies changes → Releases lock
User B: terraform apply → Waits for lock (or fails)
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.