Terraform
Intermediate 15 min read Terraform

State Management

State is Terraform's mapping from configuration to real-world resources. Master terraform.tfstate, remote state, locking, and the terraform_remote_state pattern for team infrastructure.

terraform.tfstatestateremote statestate lockingterraform_remote_statesensitivestate mv
Introduction

What is this?

Terraform stores a record of every resource it manages in terraform.tfstate. The state maps configuration addresses to real-world resource IDs, stores attribute values (including sensitive ones), and records dependencies. Every plan diffs the config against state to decide what to create, change or destroy.

Motivation

Why do you need it?

  • It maps logical config names to real resource IDs, which is essential for resources whose IDs are randomly generated.
  • It records attribute values so Terraform doesn't have to re-query every API on each run.
  • It captures dependencies, enabling correct creation and destruction ordering.
  • Remote state with locking lets a whole team work safely on the same infrastructure.
  • terraform_remote_state lets one workspace read another's outputs without duplicating resources.
Think about it

Mental model

Imagine

A home inventory ledger

Think of

Terraform state

The ledger records exactly what exists in the house — the couch in the living room, the lamp on the desk. You consult it before buying anything so you don't buy a duplicate. Terraform consults state before planning so it doesn't recreate what already exists.

Mechanics

How it works

  • During apply, Terraform creates or updates resources and writes their IDs and attributes into the state file.
  • On the next plan, Terraform reads state, refreshes resource data from the provider API, and diffs config against state.
  • Each state entry holds the resource's address, ID, attributes and metadata such as the provider version.
  • Remote backends store state in S3, Azure Blob or Terraform Cloud and add locking so concurrent runs can't corrupt it.
  • Other workspaces read it via data "terraform_remote_state" to consume outputs like VPC IDs.

How state drives the plan/apply loop.

Configuration (.tf)
State file
Diff & graph
Provider API
State updated
Reference

Key commands

terraform state list

List every resource address tracked in state.

terraform state show aws_instance.web

Show the full recorded attributes of one resource.

terraform state mv aws_instance.old aws_instance.new

Rename a resource address when refactoring config.

terraform state rm aws_instance.web

Remove a resource from state without destroying it.

terraform state pull

Download the current state to stdout as JSON.

terraform state push

Upload a local state file to the backend.

terraform force-unlock <LOCK_ID>

Release a stale state lock after verifying no run is active.

Hands-on

Examples

Remote state for a VPC, read by an app workspace

Remote state for a VPC, read by an app workspace
terraform {
backend "s3" {
bucket = "my-org-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
data "terraform_remote_state" "network" {
backend = "s3"
config = {
bucket = "my-org-terraform-state"
key = "prod/network/terraform.tfstate"
region = "us-east-1"
}
}
output "vpc_id" {
value = data.terraform_remote_state.network.outputs.vpc_id
}

The network workspace stores its state in S3 with DynamoDB locking. The app workspace reads it with terraform_remote_state and uses the published outputs, so the VPC is created once and reused everywhere.

Real world

In production

  • State lives in a remote backend (S3 + DynamoDB, Azure Blob, GCS) so teams share one source of truth.
  • Separate state per environment keeps dev problems from affecting prod.
  • terraform_remote_state shares VPC and networking outputs across application workspaces.
  • state mv and state rm support safe refactors like renaming resources or adopting existing ones.
Guidelines

Best practices

  • Never commit state; always use a remote backend once more than one person works on the infra.
  • Enable locking (DynamoDB table for S3, blob leases for Azure).
  • Use one state file per environment and per service boundary.
  • Enable server-side encryption on the state bucket and enable versioning for recovery.
  • Review state changes as part of plan output before applying.
Watch out

Common mistakes

  • Committing terraform.tfstate to git, leaking secrets into history.
  • Sharing a single state file across dev, staging and prod.
  • Hand-editing or deleting state instead of using terraform state commands.
  • Skipping encryption or versioning on the remote state bucket.
Root cause analysis

Common issues

Error
Error acquiring the state lock
Root cause

Another plan/apply holds the lock, or a crashed run left it behind.

Fix

Check for an active run; if stale, run terraform force-unlock <LOCK_ID>.

Error
Backend configuration changed
Root cause

The backend block was edited after the last terraform init.

Fix

Re-run terraform init -reconfigure to reload the backend configuration.

Error
State file locked: The state file is currently locked by another process
Root cause

Concurrent runs from CI or another engineer are using the same state.

Fix

Wait for the run to finish or release a stale lock after verifying nothing is active.

When things break

Debugging tips

  • terraform state list compared against your config reveals resources that were removed from config but still exist.
  • terraform state pull gives you raw JSON to inspect suspicious values.
  • terraform show displays the last known state in readable form.
  • Use terraform plan -refresh-only to reconcile drifted state without changing resources.
Interviews

Interview checkpoint

Practice

Hands-on lab

Master Terraform State
30 min · intermediate
In progress
Objectives
  • Inspect state with list and show
  • Refactor a resource using state mv
  • Untrack a resource with state rm and re-import it
  • Understand the danger of a stale or deleted state

Master Terraform State

30 min · intermediate

0/5 steps
0%
sandbox · Linux sandbox
$
Try these commands
Test yourself

Quick quiz

0/3
1

Which command removes a resource from state without deleting the real resource?

2

The state file may contain plaintext secrets such as database passwords.

3

Which of these prevents two engineers from corrupting the same remote state?

Quick reference

Cheat sheet

State commands
terraform state listList managed resources
terraform state show ADDRShow one resource's attributes
terraform state mv A BMove/rename an address
terraform state rm ADDRUntrack without destroying
terraform state pullDownload state as JSON
terraform force-unlock IDClear a stale lock
Go deeper

Official documentation