Chapter Three

State

The file that maps your config to real cloud objects, where it lives, how a team shares it without corrupting it, and how to keep its secrets from leaking.

8 topics

Almost every confusing thing Terraform does traces back to state. State is the file that records which real-world object — i-0abc123, a specific S3 bucket, a VPC ID — corresponds to each resource block in your config. Without it, Terraform could not compute a diff, could not tell what already exists, and could not destroy anything cleanly. With it, you inherit a new set of obligations: state holds secrets in plaintext, a team has to share one copy without two people clobbering each other, and a lost or corrupted file means Terraform no longer knows what it manages.

This chapter works through state from the inside out. What it is and why it exists, what the JSON actually contains, where to store it for a team (an S3 backend), how locking stops concurrent applies from corrupting it, what workspaces really isolate and what they do not, and the two declarative refactoring tools — import blocks and moved blocks — that let you adopt and restructure infrastructure without destroying it. The chapter closes on the uncomfortable truth that sensitive hides values from your terminal but does nothing to the bytes on disk.

Topics in This Chapter

Topic 14
What State Is and Why It Exists
The bridge between config addresses and real resource IDs. Why Terraform needs it, what it stores, and why removing a resource from state is not the same as destroying it.
State
Topic 15
The State File Anatomy
Inside the JSON: version, serial, lineage, and the resource instances. What serial and lineage guard against, and where the plaintext secrets live.
State
Topic 16
Remote State and Backends
Why the local backend disqualifies a team, the S3 backend with versioning and encryption, why backend config can't use variables, and migrating safely.
Backend
Topic 17
State Locking
The race condition concurrent applies create, native S3 locking with use_lockfile, the legacy DynamoDB table, and when force-unlock is safe.
Locking
Topic 18
Workspaces
Named separate states under one config. What they're good for, why they're a weak fit for prod-vs-dev isolation, and the risk of the active workspace being implicit.
State
Topic 19
Importing Existing Infrastructure
Bringing hand-built resources under Terraform without recreating them. Declarative import blocks, config generation, and verifying the import is clean.
State
Topic 20
Refactoring with moved Blocks
Renaming and restructuring without a destroy/recreate. The moved block as the reviewable, version-controlled alternative to state mv.
State
Topic 21
Sensitive Data in State
Why state is a secrets-exposure risk even with sensitive set. Securing the backend, minimizing secrets in state, and the OpenTofu encryption divergence.
Secrets