Skip to main content

Understanding and Managing Terraform State

Learn what the Terraform state file contains, why it is the source of truth, and how to inspect, move and remove resources without breaking things.

26 Terms

Overview and What You Will Learn

Terraform state is a JSON file, usually named terraform.tfstate, that records which real infrastructure objects Terraform manages and the attributes it last saw for each one. Terraform compares your configuration, the state, and the live cloud on every plan, so without state it could not tell what it had already created. In this lab, you will inspect state, rename a resource without destroying it, detect drift, stop managing a resource without deleting it, and recover from a lost state file.

  • What the state file contains and why it must be protected
  • Inspecting resources with terraform state list and terraform state show
  • Renaming resources with terraform state mv and moved blocks
  • Detecting drift and choosing how to resolve it
  • Removing a resource from state without destroying it
  • Rebuilding state with terraform import
  • Moving state to a remote backend

Why This Matters in Production

Picture a platform engineer at a company like Zerodha who tidies a working directory and deletes terraform.tfstate, believing it is a build artifact. The next terraform apply sees an empty state and tries to create everything again. Bucket and security group names collide, the apply fails halfway, and the environment is left half-managed. Teams avoid this with remote state, versioning and restricted access, but the underlying lesson is that state is not a cache. It is Terraform's only memory of what it owns.

Core Principles

On every plan, Terraform reconciles three things: what the configuration says, what state remembers, and what the cloud API reports right now. The difference between them is the plan you see.

flowchart TD C[.tf files
desired state] --> PL{terraform plan
compares all three} S[(State file
last known)] --> PL API[Cloud API
real now] --> PL PL --> OUT([Proposed changes]) classDef src fill:#DBEAFE,color:#1E293B classDef store fill:#475569,color:#FFFFFF classDef cloud fill:#10B981,color:#FFFFFF classDef plan fill:#F97316,color:#FFFFFF class C src class S store class API cloud class PL,OUT plan

The state file stores every attribute of every managed resource. For an EC2 instance that means the ID, AMI, IP addresses, tags and security group IDs, and for a database it can include the password. A typical entry has this shape:

Bash
version: 4
terraform_version: 1.9.8
resources:
- mode: managed
type: aws_instance
name: web
provider: registry.terraform.io/hashicorp/aws
instances:
- attributes:
id: i-0a1b2c3d4e5f6789
instance_type: t3.large
private_ip: 10.0.1.50
tags: Environment=prod, ManagedBy=terraform

The real file is JSON, shown here as an outline. Marking a variable or output sensitive hides it from CLI output but does not keep it out of state, so treat the whole file as a secret.

Different problems call for different state commands. This decision flow shows which one to reach for:

flowchart TD Q{What happened?} -->|Renamed in code| M[moved block
or state mv] Q -->|Stop managing it| R[removed block
or state rm] Q -->|Exists but untracked| I[import block
or terraform import] Q -->|Changed outside Terraform| D[plan -refresh-only] classDef dec fill:#F97316,color:#FFFFFF classDef act fill:#326CE5,color:#FFFFFF class Q dec class M,R,I,D act

Detailed Step-by-Step Practical Lab

This lab uses two empty S3 buckets, which cost nothing, and local state so you can see the file. It needs AWS credentials and permission to create buckets. Use a separate directory.

Step 1 - Create Something to Manage
HCL
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-south-1"
}
data "aws_caller_identity" "current" {}
resource "aws_s3_bucket" "web_assets" {
bucket = "mumbai-state-lab-assets-${data.aws_caller_identity.current.account_id}"
tags = {
Environment = "dev"
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket" "legacy_logs" {
bucket = "mumbai-state-lab-legacy-${data.aws_caller_identity.current.account_id}"
}
output "assets_bucket" {
value = aws_s3_bucket.web_assets.id
}
Bash
terraform init
terraform apply
Step 2 - Inspect State

List every object Terraform tracks, then show every stored attribute of one:

Bash
terraform state list
terraform state show aws_s3_bucket.web_assets

The list includes the data source as well as the two buckets. When a plan shows a change you did not expect, terraform state show tells you what Terraform currently believes about the object.

Step 3 - Rename a Resource Without Destroying It

Rename web_assets to app_assets in main.tf, including the reference in the output. If you run a plan now, Terraform proposes to destroy the old bucket and create a new one, because it sees a missing address and a new one. Tell state about the rename first:

Bash
terraform state mv aws_s3_bucket.web_assets aws_s3_bucket.app_assets
terraform plan

The plan should now report no changes. The moved block is the declarative alternative, and it records the rename in code so teammates and pipelines get it automatically. Use either the command or the block for a given rename, not both:

HCL
moved {
from = aws_s3_bucket.web_assets
to = aws_s3_bucket.app_assets
}
Tip

Prefer a moved block for refactors that other people will pull, because every workspace applies it on its next run. Use state mv for one-off fixes in a single state.

Step 4 - Create and Detect Drift

Drift means the real object no longer matches what state and configuration expect. Change a tag outside Terraform:

Bash
export BUCKET=$(terraform output -raw assets_bucket)
aws s3api put-bucket-tagging --bucket $BUCKET \
--tagging 'TagSet=[{Key=Environment,Value=dev},{Key=ManagedBy,Value=manual}]'
terraform plan

The plan shows "ManagedBy" = "manual" -> "terraform". The left side is what the cloud reports now and the right side is what your configuration wants. You have three options:

Bash
# Option 1: apply, which reverts the manual change and enforces the code
terraform apply
# Option 2: edit main.tf to accept the new tag value, then plan again
# Option 3: record the real value in state without changing infrastructure
terraform apply -refresh-only

Choose Option 1 for this lab so the later steps start from a clean plan.

Remember

-refresh-only updates state to match reality, but it does not change your configuration. If the code still disagrees, the next normal plan will propose reverting the change.

Step 5 - Stop Managing a Resource Without Deleting It

Remove legacy_logs from state first, then delete its block from main.tf so Terraform does not try to create it again:

Bash
terraform state rm aws_s3_bucket.legacy_logs
aws s3 ls | grep mumbai-state-lab-legacy
terraform plan

The bucket still exists in AWS and the plan shows no changes. In Terraform 1.7 and later, a removed block does the same declaratively. You delete the resource block, add the removed block, and run terraform apply, which drops the object from state without touching the bucket. Use either state rm or the block, not both:

HCL
removed {
from = aws_s3_bucket.legacy_logs
lifecycle {
destroy = false
}
}

Common reasons to remove from state include handing a resource to another team's configuration and moving it into a different module or workspace.

Step 6 - Back Up, Pull and Push State

Before any risky state operation, take a copy:

Bash
terraform state pull > state-backup-$(date +%Y%m%d).json

terraform state push uploads a state file, and it refuses a file whose lineage differs or whose serial is lower than the current one. Use it only to repair state, never as routine workflow.

Security

Never edit the state file by hand. It carries a serial number, lineage and internal references, and manual edits routinely corrupt it. Use state mv, state rm and import, which change state safely and write a backup first.

Step 7 - Lose State and Rebuild It

Simulate losing the file, then watch Terraform forget everything:

Bash
mv terraform.tfstate terraform.tfstate.lost
terraform plan

Terraform now proposes to create app_assets from scratch, even though the bucket exists. Rebuild state by importing the real object:

Bash
terraform import aws_s3_bucket.app_assets $BUCKET
terraform plan

In Terraform 1.5 and later, an import block does the same thing as part of a normal plan and apply. Replace the account ID below with your own, and delete the block after the apply succeeds:

HCL
import {
to = aws_s3_bucket.app_assets
id = "mumbai-state-lab-assets-123456789012"
}

With remote state and versioning, you would restore the previous state version instead of importing resource by resource.

Step 8 - Clean Up
Bash
terraform destroy
aws s3 rb s3://mumbai-state-lab-legacy-$(aws sts get-caller-identity --query Account --output text)

The second command removes the legacy bucket that Terraform no longer tracked.

Production Best Practices & Common Pitfalls

Common Mistake

Deleting or overwriting terraform.tfstate because it looks like a build artifact. Terraform then forgets every resource it owns, and a plan proposes to recreate all of them.

Security

State contains plaintext values, including passwords and keys that resources use. Restrict read access to the state bucket to the pipeline role and a few administrators, and encrypt it at rest.

  • Use remote state with locking for teams. Move off local state before a second engineer joins, and check the backend documentation for the currently recommended locking setup.
  • Turn on versioning for the state bucket. A versioned bucket lets you restore an earlier state after a bad apply or a corrupt file.
  • Back up before surgery. Take a terraform state pull copy before any mv, rm or large refactor.
  • Prefer declarative blocks. moved, removed and import blocks are reviewable in a pull request, while ad hoc state commands leave no trace in code.
  • Run a drift check on a schedule. A scheduled terraform plan -refresh-only in CI shows out-of-band changes before they surprise you.
  • Keep state versions aligned. A state file written by a newer Terraform cannot be read by an older one, so pin the same version across the team.

To move local state to an S3 backend, add a backend block, then let init copy the existing state across. Confirm the locking option against the backend documentation for your Terraform version:

HCL
terraform {
backend "s3" {
bucket = "mumbai-tfstate-prod-123456789012"
key = "prod/network/terraform.tfstate"
region = "ap-south-1"
encrypt = true
use_lockfile = true
}
}
Bash
terraform init -migrate-state

Quick Reference & Troubleshooting Commands

Command Description
terraform state list List all objects tracked in state
terraform state show ADDRESS Show every stored attribute of one object
terraform state mv SRC DST Rename or move an object in state only
terraform state rm ADDRESS Stop tracking an object without destroying it
terraform state pull Print the current state, useful for backups
terraform state push FILE Upload a state file, for repairs only
terraform import ADDRESS ID Add an existing object to state
terraform plan -refresh-only Show drift without proposing changes
terraform init -migrate-state Copy existing state into a newly configured backend
terraform force-unlock LOCK_ID Release a stuck lock after confirming nothing is running
Error Cause Fix
Plan shows everything as new State is empty or lost Restore a backup or import the resources
state snapshot was created by Terraform vX, which is newer State written by a newer version Upgrade the CLI to that version or later
Resource already managed by Terraform on import The address is already in state Check terraform state list first
Error acquiring the state lock Another run holds the lock Wait, or use force-unlock if it is stuck
Cannot import non-existent remote object Wrong ID or region Check the ID format in the provider docs
Plan wants to destroy and recreate after a rename State still has the old address Add a moved block or run state mv

Resources

Explore More in Terraform State and Backend Management

All 3 Topics

Frequently Asked Questions

Is Understanding and Managing Terraform State free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Understanding and Managing Terraform State topic cover?

Learn what the Terraform state file contains, why it is the source of truth, and how to inspect, move and remove resources without breaking things.

Found a mistake, an outdated step or a broken link?