How it works
The explanation, with examples you can run.
What is inside
From the local demo used in this path (Terraform 1.5.7), abridged:
{ "version": 4, "terraform_version": "1.5.7", "serial": 3, "lineage": "86a3d8b9-6ec5-a133-dac0-a7eeb9bf9b0a", "resources": [ { "mode": "managed", "type": "random_pet", "name": "name", "provider": "provider[\"registry.terraform.io/hashicorp/random\"]", "instances": [ { "schema_version": 0, "attributes": { "id": "dev-known-woodcock", "length": 2, "prefix": "dev", "separator": "-" } } ] } ]}- lineage is a unique ID for this state's history; serial increases on every write. Terraform refuses to replace a state with one of a different lineage or a lower serial unless forced.
- attributes are everything the provider returned, including computed values and secrets.
- Dependencies between instances are recorded too, so Terraform can destroy objects in the right order even after their blocks are deleted from the configuration.
Working with state safely
terraform state list # every address in stateterraform state show random_pet.service # one object's attributesterraform state mv OLD NEW # rename an address (prefer a moved block)terraform state rm ADDRESS # forget an object, leave it running (prefer a removed block)terraform state pull > backup.tfstate # copy the current remote stateConfiguration-driven alternatives (moved, import and removed blocks, covered in the refactoring topic) are better for anything routine, because they go through a plan and code review like any other change. Keep the state subcommands for repairs.
Do not edit the JSON by hand. It is easy to break the structure, forget the serial or leave dependencies pointing at nothing, and a bad state can make the next apply destroy things. If you must repair one, pull a backup first, change it with the CLI, and verify with a plan that shows no unexpected changes.
The rules that follow
- One writer at a time. Two simultaneous applies against one state lose updates or corrupt it. Use a backend with locking (next topic).
- Store it remotely, versioned. A laptop's
terraform.tfstateis one disk failure from orphaning your infrastructure, and nobody else can run a plan. - Keep it out of Git. It contains secrets, and merges of state files are meaningless.
- Keep states small. One state per environment and per area (network, data, apps) limits the blast radius of a bad apply and keeps plans fast.
- Restrict access. Read access to state is read access to every secret in it.
Check yourself
3 questions. Get them all right to finish this topic.
0 of 3 right so far. Get all three to finish this topic.