Terraform Tutorial · State and Workflow · Lesson 16 of 25

Terraform State

The state file is how Terraform remembers what it manages. Learn what's in it, why it matters, and the commands to inspect it safely.

What is state?

After apply, Terraform writes terraform.tfstate: a JSON record mapping each resource in your configuration to the real object (for example aws_instance.web → i-0abc…), with its attributes. On the next plan, Terraform compares configuration, state and reality to work out what to change.

Rules for state

  • Don't edit it by hand. Use the terraform state commands.
  • Don't commit it to Git. It can contain secrets (passwords, keys) in plain text.
  • Store it remotely when more than one person or a CI pipeline runs Terraform (next lesson).
  • One state per environment (dev, staging, prod), so a mistake in dev can't touch prod.

Inspecting state

terraform state list                      # every resource address
terraform state show aws_instance.web     # one resource's attributes
terraform output                          # outputs
terraform show                            # everything, human readable
Outputs are stored in state too
# Values in state are what later plans compare against:
locals {
  deployed_version = "1.4.2"
}

output "deployed_version" {
  value = local.deployed_version
}

Output

deployed_version = "1.4.2"

Run this on your computer — see “Get Started” for setup.

Drift

If someone changes infrastructure outside Terraform (in the console), the next plan shows the difference and proposes to put it back. terraform plan -refresh-only shows drift without proposing changes, and terraform apply -refresh-only accepts the real values into state.

Test yourself

Why shouldn't terraform.tfstate be committed to Git?

  1. It is too large
  2. It can contain secrets in plain text
  3. Git can't store JSON
  4. Terraform deletes it
Show answer

Answer: It can contain secrets in plain text