State: what Terraform remembers
Terraform · 13 questions
Short notes
Key idea
The state file is Terraform's record of which real resources belong to which blocks in your code. Every plan compares code, state and reality. Lose or corrupt the state and Terraform no longer knows what it manages.
Syntax
terraform {
backend "gcs" {
bucket = "my-project-tfstate"
prefix = "data-platform"
}
}
terraform state list
terraform state show google_storage_bucket.raw
terraform state mv old.name new.name
terraform state rm google_storage_bucket.raw # forget, don't delete
Example
A team keeps state in a GCS bucket with versioning on. Two people run apply at once: the backend locks the state, so the second waits instead of corrupting it.
Traps
- Never commit
terraform.tfstateto Git; it can contain passwords and keys. - Local state on a laptop can't be shared and dies with the laptop.
- Don't hand-edit the state file; use
terraform statecommands. - Turn on bucket versioning for the state bucket so a bad write can be undone.
Want the full lesson with step-by-step examples, a project and a certificate? Terraform course, ₹120 →
- Question 1easy
What is Terraform state mainly for?
- Question 2medium
You delete a resource's block from your code. How does Terraform still know how to destroy it in the right order?
- Question 3easy
Why is local state a problem for a team of three?
- Question 4medium
Why turn on object versioning for the state bucket?
- Question 5hard
You write
bucket = var.state_bucketinsidebackend "gcs". What happens?
State: what Terraform remembers
State: what Terraform remembers
State: what Terraform remembers
State: what Terraform remembers
State: what Terraform remembers
8 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.