Skip to content
Advanced IaCLesson 3 of 5 2 min read

State Management

Why Terraform keeps a map of what it already built, and why that file deserves the same care as a credential.

On this page5 sections

Terraform's configuration describes what you want. Its state file records what it already built - and that distinction turns out to matter a lot.

What state actually is

Every time terraform apply creates a resource, Terraform writes an entry into terraform.tfstate mapping your configuration's name for it (aws_instance.web) to the real resource ID the cloud provider assigned. On every future plan, Terraform reads that file to know what already exists, so it can compute an accurate diff instead of trying to recreate everything from scratch.

Why it needs real care

  • It often contains secrets. Resource attributes - a generated database password, a private key - can end up in state in plain text. It deserves the exact same handling as any other credential file.
  • Never hand-edit it. The file's format isn't meant for manual editing, and small corruption here can make Terraform lose track of real infrastructure entirely, leading it to try to recreate resources that already exist.
  • Concurrent runs corrupt it. If two people run apply at the same time against the same state, they can race and corrupt it.

Remote state

For any team beyond a single person, state lives in a remote backend - commonly cloud object storage (like S3) paired with a locking mechanism (like a DynamoDB table) that prevents two applys from running at once. Everyone's Terraform runs then read and write the same shared, locked copy, instead of each having their own out-of-sync local file.

Drift

Drift is what happens when real infrastructure stops matching the state Terraform believes is true - usually because someone changed something by hand in the cloud console. The next terraform plan will show that difference clearly, which is exactly why teams that take IaC seriously treat console changes as a last resort, not a habit.

Try it

Run these in the practice terminal (opens in a new tab). It opens in a new tab, so you keep your place here.
bash
chmod 600 terraform.tfstate

When you're ready, hit Mark complete and move to the next lesson.

Challenge

Lock down terraform.tfstate so only its owner can read or write it - it often contains sensitive resource data in plain text.

Want to experiment first? Try things in the practice terminal (opens in a new tab), then enter the command that solves the task here.

Quiz

Lock in the concepts. Score at least 80% to mark the lesson complete.

0 of 2 answered

Done with this one?

Skipped the challenge? You can mark the lesson complete by hand.

Your notes

Kept on this browser only.