State: Terraform's memory
What the state file is and why Terraform needs it, how teams share it safely with a remote backend and locking, and how to rename, import and forget resources without breaking anything.
By the end of this lesson you'll be able to
0 of 5 completeVerified lab: state list and show, the state-lock clash, moved, import (and the import that's not supported) and state rm. Run on Terraform 1.17.1; the output shown is real.
Code walkthrough: the S3 backend block: explained, not run.
Cloud lab: an S3 backend needs an AWS account and a bucket.
Why state exists
State is the part of Terraform that surprises people most, and the part that causes the worst incidents when it's handled badly. It's worth seeing the problem one step at a time.
The problem: code alone doesn't know what it owns
Your code says resource "aws_instance" "web". The AWS account has three running instances: one
made in the console last year, one from another team, one left over from a test. Which one is
"web"? If Terraform guessed, it could modify or delete someone else's server.
The fix: a state file maps addresses to real IDs
After every apply, Terraform writes down each resource address and the real object it created:
aws_instance.web is i-07c2, with all its attributes. Next time, it only looks at i-07c2, and
the other instances are never touched.
The new problem: a file on a laptop breaks in a team
By default the state is terraform.tfstate on whoever ran apply. A teammate with an old copy, or
none, runs apply at the same time, and Terraform happily creates a second server, because their
state says there isn't one.
The fix for teams: remote state with a lock
The state moves to one shared place, such as an S3 bucket, and every run takes a lock first. Only one writer at a time; everyone else waits.
In this lesson you'll look inside real state, hit a real lock, and learn the safe ways to rename, import and forget resources.
What state is
The state file is JSON. Here's the start of the lab's, after creating one file:
{ "version": 4, "terraform_version": "1.17.1", "serial": 1, "lineage": "967442eb-1a4e-b21a-d36f-7667ac820f19", "outputs": {}, "resources": [ { "mode": "managed", "type": "local_file", "name": "web", "provider": "provider[\"registry.terraform.io/hashicorp/local\"]", "instances": [ { "schema_version": 0, "attributes": { "content": "web server\n",
serialgoes up on every change, so Terraform can refuse to overwrite newer state with older.lineageis a unique ID for this state's history, so you can't accidentally push a completely different project's state over it.resourceslists every managed object with its type, name, provider and all its attributes.
Never edit it by hand. Use the commands, which read it for you. The resource behind this state sets safe permissions explicitly, instead of taking the provider's default:
resource "local_file" "web" { filename = "${path.module}/out/web.txt" content = "web server\n" file_permission = "0600" # owner read/write only directory_permission = "0700" # owner only }
$ terraform state list local_file.web $ terraform state show local_file.web # local_file.web: resource "local_file" "web" { content = <<-EOT web server EOT ... directory_permission = "0700" file_permission = "0600" filename = "./out/web.txt" id = "b98caeeaab8b12bc7123853e05f2dfcc547c6ecd" } $ ls -ld out out/web.txt drwx------ out -rw------- out/web.txt
terraform state listterraforminfrastructure as code
ls -ld out out/web.txtlslist files
(The ... hides six checksum attributes of the content.) state show prints what Terraform recorded;
ls confirms the real file matches: only the owner can read it.
Besides the ID mapping, state caches attributes (so plan can compare without asking for everything again) and remembers dependencies (so destroy happens in the right order even after you delete the code).
Left unset, local_file creates files and folders with 0777: anyone on the machine can read and
change them. That default appears in some plan output in lesson 9. Don't rely on it. Set
file_permission = "0644" for ordinary files and "0600" (with directory_permission = "0700")
for anything private. For secrets, local_sensitive_file defaults to 0700, as the Security lesson
shows. The same thinking applies to terraform.tfstate itself on a laptop: keep it readable only by
you, and better, keep it in a remote backend.
Remote state and locking
A backend decides where state lives. For AWS teams the usual choice is S3:
# backend.tf terraform { backend "s3" { bucket = "acme-terraform-state" key = "shop/prod/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true # lock with a .tflock object in the same bucket } }
What each setting does:
bucketandkey: where the file goes. One bucket holds many states; the key separates them (shop/prod/...,shop/dev/...).encrypt: server-side encryption, because state holds secrets.use_lockfile: native S3 locking, available since Terraform 1.10. Older setups used a DynamoDB table (dynamodb_table), which is now deprecated.
Create the bucket once, outside this configuration, with versioning on (so you can roll back a
corrupted state) and public access blocked. Then run terraform init, and with existing local state,
terraform init -migrate-state copies it up. Other good backends: HCP Terraform, Azure Storage
(azurerm), Google Cloud Storage (gcs).
A real lock
Every backend that supports it locks during writes; even the local backend does. In the lab, one terminal ran an apply that takes 12 seconds, and a second terminal ran plan meanwhile:
$ terraform plan Error: Error acquiring the state lock Error message: resource temporarily unavailable Lock Info: ID: 8da76c6d-c1c4-4393-d885-86b285980ed6 Path: terraform.tfstate Operation: OperationTypeApply Who: rajeev@Elonerajeev Version: 1.17.1 Created: 2026-11-08 15:39:00.604349637 +0000 UTC Info: Terraform acquires a state lock to protect the state from being written by multiple users at the same time. Please resolve the issue above and try again. For most commands, you can disable locking with the "-lock=false" flag, but this is not recommended.
terraform planterraforminfrastructure as codeplanpreview changes
The lock says who holds it, for which operation and since when. Wait for it. If a run crashed and
left a stale lock, and you're sure nothing is running, release it with
terraform force-unlock 8da76c6d-c1c4-4393-d885-86b285980ed6. Never use -lock=false on shared
state.
Moving and importing
Code changes over time, and state has to follow without destroying anything real.
Rename with a moved block
Renaming local_file.web to local_file.frontend looks, to Terraform, like "destroy web, create
frontend". A moved block says it's the same object:
resource "local_file" "frontend" { filename = "${path.module}/out/web.txt" content = "web server\n" file_permission = "0600" directory_permission = "0700" } moved { from = local_file.web to = local_file.frontend }
$ terraform plan local_file.frontend: Refreshing state... [id=b98caeeaab8b12bc7123853e05f2dfcc547c6ecd] Terraform will perform the following actions: # local_file.web has moved to local_file.frontend resource "local_file" "frontend" { id = "b98caeeaab8b12bc7123853e05f2dfcc547c6ecd" # (10 unchanged attributes hidden) } Plan: 0 to add, 0 to change, 0 to destroy.
terraform planterraforminfrastructure as codeplanpreview changes
Same ID, nothing created or destroyed. Moved blocks also handle moving a resource into a module
(to = module.site.local_file.page). The older command terraform state mv does the same thing
directly on state, but a moved block is reviewed in a pull request and works for everyone who runs
the code. Keep moved blocks for a while, so every environment picks them up.
Adopt existing resources with an import block
Something was created by hand and you want Terraform to manage it. Write the resource, and an
import block with its real ID. The lab imported a port number another team had already chosen:
import { to = random_integer.app_port id = "8443,8000,8999" } resource "random_integer" "app_port" { min = 8000 max = 8999 }
$ terraform plan random_integer.app_port: Preparing import... [id=8443,8000,8999] random_integer.app_port: Refreshing state... [id=8443] Terraform will perform the following actions: # random_integer.app_port will be imported resource "random_integer" "app_port" { id = "8443" max = 8999 min = 8000 result = 8443 } Plan: 1 to import, 0 to add, 0 to change, 0 to destroy. $ terraform apply -auto-approve ... random_integer.app_port: Importing... [id=8443,8000,8999] random_integer.app_port: Import complete [id=8443,8000,8999] Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
terraform planterraforminfrastructure as codeplanpreview changes
terraform apply -auto-approveapplymake the changes-auto-approveskip the yes prompt
The ID format is different for each resource type; the provider docs have an "Import" section at the
bottom of each page (for an EC2 instance it's the instance ID, i-0abc...). After import, a plan
should say "No changes": if it wants to change things, your code doesn't match reality yet. Two
helpers: terraform plan -generate-config-out=generated.tf writes the resource code for you, and not
every resource supports import at all. In the lab, local_file refused:
Error: Resource Import Not Implemented This resource does not support import. Please contact the provider developer for additional information.
Forget a resource
To stop managing something without deleting it, for example handing it to another team's configuration:
$ terraform state rm random_integer.app_port Removed random_integer.app_port Successfully removed 1 resource instance(s).
terraform state rm random_integer.app_portterraforminfrastructure as code
The real object keeps running. In code, a removed block with lifecycle { destroy = false } does
the same and gets reviewed like any other change.
State best practices
- Never commit state to Git. It can contain passwords and keys in plain text, and Git can't lock.
- Use a remote backend with locking, encryption and versioning for anything shared.
- Restrict who can read the state bucket. Reading state means reading every secret in it.
- One state per environment and per area. A small state plans faster and limits the damage of a mistake (lesson 15).
- Change state with code (
moved,import,removedblocks) rather than ad-hocstatecommands, so changes are reviewed. - Never edit the JSON by hand. If you must,
terraform state pull > backup.tfstatefirst.
If the state is lost, Terraform forgets everything it manages. The next apply tries to create it all again, and fails or makes duplicates. Bucket versioning is your undo button. Turn it on before the first apply.
Rename, import and forget, without breaking anything
In a test project, apply one local_file, rename it with a moved block, import a random_integer with an import block, then state rm it. After each step, run terraform plan and confirm it says 0 to add, 0 to change, 0 to destroy (or 1 to import). Record each plan's summary line.
~/state-notes.txtReveal one safe solution
$ terraform plan -no-color | grep -E 'has moved|imported|Plan:|No changes' >> ~/state-notes.txt $ terraform apply -auto-approve $ terraform state list >> ~/state-notes.txt $ terraform state rm random_integer.app_port >> ~/state-notes.txt
terraform plan -no-color | grep -E 'has moved|imported|Plan:|No changes' >> ~/state-notes.txtterraforminfrastructure as codeplanpreview changes|pipe: send output to the next commandgrepfind lines that match a pattern>>append output to a file
terraform apply -auto-approveapplymake the changes-auto-approveskip the yes prompt
In the lab, the rename planned 0 to add, 0 to change, 0 to destroy and the import 1 to import.
If the rename shows 1 to add and 1 to destroy, the moved block's from doesn't match the old
address exactly.
Try it yourself
0 of 6 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
Why does Terraform need a state file?
Official reading for this lesson
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.