Table of Contents

What Is Terraform State?

Terraform state is a JSON file that maps your configuration to real-world infrastructure. It tracks which resources Terraform manages, their current attributes, and dependencies between them.

Why Does Terraform Need State?

  1. Mapping configuration to reality — state records which real resource corresponds to each resource block
  2. Performance — state caches attribute values so Terraform doesn’t query every resource on every plan
  3. Dependency tracking — state tracks the order resources must be created or destroyed

Where Is State Stored?

By default, state is stored locally in terraform.tfstate. For teams, use a remote backend:

S3 Backend (Most Common)

terraform {
  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

Other Backends

  • Terraform Cloud — managed state with UI, RBAC, and run history
  • GCS — Google Cloud Storage with built-in locking
  • Azure Blob — Azure Storage with lease-based locking
  • Consul, PostgreSQL, HTTP — for specialized setups

State Locking

State locking prevents concurrent modifications. When one user runs terraform apply, others are blocked until the lock is released.

If a lock gets stuck:

terraform force-unlock LOCK_ID

Essential State Commands

terraform state list                    # List all resources in state
terraform state show aws_instance.web   # Show details of one resource
terraform state mv old.name new.name    # Rename a resource in state
terraform state rm aws_instance.old     # Remove resource from state (doesn't destroy it)
terraform state pull                    # Download remote state to stdout
terraform state push                    # Upload local state to remote
terraform import aws_instance.web i-123 # Import existing resource into state

Best Practices

  • Always use remote state for team projects
  • Enable encryption at rest for state files
  • Enable locking to prevent concurrent modifications
  • Never edit state manually — use terraform state commands
  • Separate state per environment — dev, staging, and prod should never share state
  • Back up state — enable versioning on your S3 bucket

Learn More