🎓 A1Learner
🔍
0 of 50 lessons completed

What Is Terraform State?

Terraform state is the record that maps a configuration to the real objects it manages. Without it, Terraform cannot tell what already exists.

State appears after the first apply

List the folder after an apply to see the new file.

terraform apply -auto-approve
ls -l terraform.tfstate

A peek inside the file

State is JSON. Each resource has a type, a name, and attributes.

{
  "version": 4,
  "resources": [
    {
      "type": "local_file",
      "name": "hello"
    }
  ]
}

State is not for hand editing

Edit the configuration, not the file. Terraform keeps the file in step.

# Do not edit terraform.tfstate by hand.
# Change main.tf and run terraform apply.

Example

# main.tf
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.0"
    }
  }
}

resource "local_file" "hello" {
  content  = "Hello."
  filename = "${path.module}/hello.txt"
}

# commands
terraform init
terraform apply -auto-approve
ls -l terraform.tfstate

Key points

  • State lives in a file named terraform.tfstate. Terraform writes it on the first apply.
  • The file holds resource names, IDs, and attributes. It is the memory of the last apply.
  • A plan compares three things: the configuration, the state, and the real world.
  • State lets Terraform update a resource instead of creating a second one.
  • Delete the state and Terraform forgets the objects. The objects keep running, unmanaged.

The apply creates the file and writes the state file beside it. State records the file that now exists. A second apply would find the file already there and change nothing.

Note

state is a record, not a backup. The configuration is still the source of truth.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does Terraform use state for?