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:
graph LR
A["Your Configuration (.tf)<br/>aws_instance.web<br/>type: t3.micro"] <--> B["State File (.tfstate)<br/>id: i-0abc123<br/>type: t3.micro"]
B <--> C["Real Infrastructure<br/>EC2 Instance<br/>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:
graph LR
A1["User A: terraform apply"] --> A2["Acquires lock"]
A2 --> A3["Applies changes"]
A3 --> A4["Releases lock"]
B1["User B: terraform apply"] --> B2["Waits for lock (or fails)"]
If a lock is stuck (e.g., after a crash), you can force-unlock:
terraform force-unlock <lock-id>
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.