Terraform Field Guide · Chapter 3 of 12
State: what Terraform remembers
Terraform keeps a file that maps every block in your code to a real resource. Lose it and Terraform forgets what it built; share it carelessly and two people overwrite each other. What state is, where it belongs, how locking works, and the commands that fix it safely.
- 45 min
- Beginner
- Hands-on
- Free
By Joshua Sequeira, founding engineer running Terraform in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
Why state exists
Your code says aws_instance.web. AWS says i-0a1b2c3d4e5f67890. Nothing in AWS records that the two are the same thing. Terraform has to remember it, and it does that in the state file, terraform.tfstate.
State does three jobs:
- Mapping. Each block in your code points at one real resource ID. This is how plan knows "update this instance" rather than "create another one".
- Metadata. It records what depends on what, so Terraform can destroy things in the right order even after you have deleted the code that described them.
- A cache. It keeps the last known attributes of everything, so Terraform can compare and show you what changed.
The picture at the top of the page is the whole idea: code, state and reality, with state in the middle holding them together.
What is inside
State is JSON. You should almost never edit it by hand, but you should be able to read it:
{
"version": 4,
"serial": 42,
"lineage": "3f6c1e2a-8b4d-4c1f-9a7e-0d2b5c8e1f43",
"resources": [
{
"mode": "managed",
"type": "aws_instance",
"name": "web",
"provider": "provider[\"registry.terraform.io/hashicorp/aws\"]",
"instances": [
{
"index_key": 0,
"attributes": {
"id": "i-0a1b2c3d4e5f67890",
"instance_type": "t3.small",
"private_ip": "10.0.1.24",
"subnet_id": "subnet-0f1e2d3c"
},
"dependencies": ["aws_subnet.app"]
}
]
}
]
}- Goes up by one on every write. terraform state push refuses to replace a state that has a higher serial.
- A unique ID for this state's history. Stops you from pushing one project's state over another's.
- The mapping: aws_instance.web[0] is this instance.
- Metadata for ordering. This instance was created after the subnet, so it will be destroyed before it.
Remote state
By default, state is a file next to your code. That is fine for learning and wrong for a team: it lives on one laptop, it is lost with that laptop, and nobody else can see it. A backend moves it somewhere shared.
terraform {
backend "s3" {
bucket = "acme-terraform-state"
key = "network/terraform.tfstate"
region = "eu-west-1"
encrypt = true
use_lockfile = true
}
}- Store state in an S3 bucket. Other backends include HCP Terraform, Google Cloud Storage and Azure Blob Storage.
- The path inside the bucket. One bucket can hold state for many projects and environments, each under its own key.
- Encrypt the state object at rest.
- Native S3 locking: Terraform writes a .tflock object next to the state while it runs. Older setups used a DynamoDB table for this, which is now deprecated.
Three settings on the state bucket itself matter as much as the backend block: turn on versioning so you can restore an older state if one is ever corrupted, block public access, and limit who can read it. The bucket is usually created once, by hand or by a tiny separate configuration, because Terraform cannot store its state in a bucket that does not exist yet.
Locking
Shared state solves one problem and creates another: two people can now change the same file at the same time. Play the same morning three ways:
Interactive · Two applies at once
Priya and Sam both apply a change at 10am. Where is the state?
State what Terraform remembers
AWS what really exists
With locking on, the person who has to wait sees exactly who holds the lock and what they are doing:
terraform apply
│ Error: Error acquiring the state lock
│
│ Lock Info:
│ ID: 7c1d6e0a-5b2f-4e8d-9c3a-1f0e2d4b6a8c
│ Path: acme-terraform-state/network/terraform.tfstate
│ Operation: OperationTypeApply
│ Who: priya@priya-laptop
│ Created: 2026-11-15 10:00:05 UTC
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time.Who- Ask this person before doing anything else.
terraform force-unlock <ID>- Removes a stuck lock. Only for a run you know has died, such as a CI job that was cancelled mid-apply. Forcing a live lock brings back the race above.
The state commands
When state and reality disagree, fix state with these commands, never with a text editor:
| Command | What it does | Touches real resources? |
|---|---|---|
terraform state list | Every address in state | No |
terraform state show ADDR | All recorded attributes of one resource | No |
terraform state mv A B | Renames an address, so a refactor does not destroy and recreate | No |
terraform state rm ADDR | Forgets a resource. It keeps running, unmanaged | No |
terraform state pull | Prints the current remote state, handy for a backup before surgery | No |
None of these change your cloud account, and that is the point: they change what Terraform believes. For renames and imports, chapter 8 shows moved and import blocks, which do the same thing through a reviewed plan instead of a one-off command.
Hands-on: inspect and move state
Use the folder from chapter 2 (random_pet plus local_file), applied, so there is something in state.
terraform state list
terraform state show random_pet.server
local_file.inventory
random_pet.server
# random_pet.server:
resource "random_pet" "server" {
id = "proud-gecko"
length = 2
separator = "-"
}state list- Every address Terraform manages here.
state show- The recorded attributes, formatted like HCL.
Now see what "forgetting" means. Remove the file from state, then plan:
terraform state rm local_file.inventory
ls inventory.txt
terraform plan
Removed local_file.inventory
Successfully removed 1 resource instance(s).
inventory.txt
# local_file.inventory will be created
+ resource "local_file" "inventory" {
Plan: 1 to add, 0 to change, 0 to destroy.ls inventory.txt- The real file is still there. rm only changed Terraform's memory.
will be created- Terraform no longer knows the file exists, so it plans to create it. On AWS, this is how you end up with duplicates or "already exists" errors.
Run terraform apply to take it back under management (the local provider simply overwrites the file).
Finally, move state somewhere else without losing anything. Add a backend block to main.tf:
terraform {
backend "local" {
path = "state/dev.tfstate"
}
}- Still on disk, but at a path you choose. Swapping this for an s3 block is the same migration.
mkdir -p state
terraform init -migrate-state
terraform plan
Initializing the backend...
Do you want to copy existing state to the new backend?
Enter a value: yes
Successfully configured the backend "local"!
No changes. Your infrastructure matches the configuration.-migrate-state- Copies the existing state to the new backend. Moving from local to S3 works exactly the same way.
No changes- The proof the move worked: same resources, same IDs, new location.
Mini mission
Rename a resource without recreating it
Rename random_pet.server to random_pet.web in your code (and in the reference inside local_file). Run plan first and look at what it wants to do. Then get plan to say No changes without undoing the rename.
Reveal one safe solution
terraform plan # before: 2 to add, 2 to destroy
terraform state mv random_pet.server random_pet.web
terraform plan
Move "random_pet.server" to "random_pet.web"
Successfully moved 1 object(s).
No changes. Your infrastructure matches the configuration.Without the move, Terraform sees one resource removed and a new one added, so the pet gets a new random name and the file is rewritten. state mv tells it they are the same thing. In chapter 8 you will do the same with a moved block, which goes through review like any other change.
Check yourself
Quiz
0 of 5 answered