Foundations / Lesson 3 of 3
State
Understand how Terraform remembers what it built, and why that memory matters.
8 min Intermediate 8 steps
IN THIS LESSON
Step 1 of 8
STEP 1 / 8
Desired state: your configuration
Your .tf files describe how things should be. This is the desired state, and it is the only part you write by hand.
← → step · R replay · Space play/pause
YOU'LL LEARN
- What the state file records
- How Terraform compares configuration, state and reality
- Why teams keep state in a remote backend
- How locking and access control protect it
- Desired state: your configuration. Your .tf files describe how things should be. This is the desired state, and it is the only part you write by hand.
- Actual state: the real world. Meanwhile, real servers and databases already exist in your cloud account. Terraform needs a way to know which of them it is responsible for.
- State links the two. Terraform keeps a state file that maps each resource address in your configuration to the real object it created, using the provider's ID, plus the attributes it last saw. Without it, Terraform could not tell its own resources from anyone else's.
- A plan compares all three. When you run terraform plan, Terraform refreshes what it knows by reading the real objects, then compares your configuration against the state. The difference is the plan: the exact changes needed to make reality match the code.
- Share state with your team. A state file on one laptop breaks teamwork, because two people would plan against two different views of reality. A remote backend, such as an S3 bucket, keeps a single shared copy that everyone uses.
- Locking prevents clashes. If two applies run at once they could overwrite each other's changes. Backends that support locking take a lock before any operation that writes state, so the second run waits or fails instead of corrupting it.
- Treat state as sensitive. State can contain sensitive values, such as database passwords, in plain text. Keep it out of Git, encrypt the backend, and restrict who can read it.
- Recap. State is Terraform's memory. Look after it as carefully as the infrastructure it describes.