Skip to content

Advertisement

DevOps Society

Terraform State Explained: Remote Backends, Locking and Fixing Drift

Terraform state is the file that decides what Terraform thinks exists. How it works, why it must live in a remote backend with locking, and how to recover when state and reality disagree.

Published your local timeupdated

Terraform State Explained: Remote Backends, Locking and Fixing Drift

Most Terraform horror stories are really state stories. Someone ran apply from their laptop with an old state file. Two pipelines ran at the same time. A resource got renamed in code and Terraform decided to destroy the production database and create a new one. The code was fine in every case. The state was not.

If you understand state, Terraform becomes a lot less scary. This is the explanation we wish we had been given on day one.

What the state file is for

Terraform code describes what you want. The real world is what your cloud provider actually has. The state file is Terraform's memory of how the two map onto each other: this aws_s3_bucket.logs block in your code is that bucket with that ARN in that account.

Every plan works by reading the state, refreshing it against the provider's API, and comparing the result with your code. No state, no mapping, and Terraform assumes nothing exists yet.

The state file also holds attribute values, and some of those are sensitive: database passwords, generated keys, connection strings. Treat state as a secret, not as a build artefact.

Why local state does not survive a team

By default Terraform writes terraform.tfstate next to your code. That is fine for a tutorial. For anything shared it fails in predictable ways: two people have two different copies, someone commits it to Git with secrets inside, a laptop dies and the mapping is gone.

The fix is a remote backend with locking. On AWS the usual choice is S3. Recent Terraform versions can lock using an S3 lock file directly, so a separate DynamoDB table is no longer required.

terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "network/prod/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true
  }
}

A few settings matter more than they look. Turn on versioning on the bucket so you can roll back a bad write. Block all public access. Restrict who can read the bucket, because reading state means reading secrets. On Azure, GCS or Terraform Cloud the details differ, but the same three rules apply: remote, locked, versioned.

How big should one state be?

One giant state for everything means every plan is slow, every change risks everything, and one person's lock blocks the whole team. One state per resource is the opposite problem. A reasonable split is by environment and by layer: network, data stores, compute and app config for each of dev, staging and prod. Things that change together live together. Things owned by different teams live apart.

Pass values between states with outputs and data sources or a small shared parameter store, rather than reaching into another team's state file.

Drift: when reality moves

Drift is when the real infrastructure no longer matches what the state and code say. Someone added a security group rule in the console during an incident. An autoscaler changed a value. A script tagged everything.

You will see drift as changes in a plan that nobody made in code. You have three options for each one:

  • Revert it by applying the code as is, if the manual change was a mistake.

  • Adopt it by updating the code to match, if the change was right.

  • Ignore it with lifecycle { ignore_changes = [...] }, if something outside Terraform legitimately owns that field, such as a desired count managed by an autoscaler.

Running a scheduled terraform plan -detailed-exitcode in CI is a cheap drift detector. Exit code 2 means there are changes, and that can open a ticket instead of waiting for someone to trip over it.

The state commands you will actually need

Renaming without destroying. If you rename a resource block or move it into a module, Terraform will plan to destroy the old one and create a new one. Add a moved block instead:

moved {
  from = aws_db_instance.main
  to   = module.database.aws_db_instance.this
}

This is safer than running terraform state mv by hand, because it is reviewed in a pull request like any other change.

Bringing existing resources under Terraform. Use an import block, then run plan until it shows no changes:

import {
  to = aws_s3_bucket.logs
  id = "acme-prod-logs"
}

Letting go of a resource without deleting it: terraform state rm, or a removed block in newer versions. Useful when handing a resource to another team's state.

When state gets corrupted

It happens rarely, usually because of an interrupted apply or a manual edit. With bucket versioning on, recovery is mostly calm: pull the previous version of the state object, put it back, and run a plan to see what changed since. Never hand-edit a state file in production unless you have a copy, a second person watching and a very good reason.

And never run terraform force-unlock just because a lock is in the way. Find out who holds it first. The lock is usually there because something is still running.

For the wider picture of how infrastructure code fits into delivery, see our guide to the CI/CD pipeline from commit to production.

Quick answers

What is Terraform state?

Terraform state is a file that maps each resource in your Terraform code to the real object in your cloud account, along with its attributes. Terraform uses it to work out what to create, change or destroy.

Do I still need DynamoDB for Terraform state locking on AWS?

Not with recent Terraform versions. The S3 backend can lock using a lock file in the bucket by setting use_lockfile to true, so a separate DynamoDB table is optional.

How do I rename a Terraform resource without destroying it?

Add a moved block that points from the old address to the new one. Terraform then updates the state instead of planning a destroy and create.

Advertisement

Follow DevOps Society on LinkedIn

Practical infrastructure engineering in your feed.

Follow

Written by

DevOpsSociety Editorial Team

Editorial Team

The DevOpsSociety Editorial Team covers DevOps, cloud infrastructure, Kubernetes, AI infrastructure, platform engineering, cybersecurity, FinOps, and modern engineering practices. We publish practical insights, technical guides, architecture analysis, and research for engineers and technology leaders.

More from DevOpsSociety →
The Infrastructure Briefing

Get the infrastructure briefing.

Practical DevOps, cloud, AI infrastructure and engineering insights, delivered weekly. Read by engineers and engineering leaders.

No spam. Unsubscribe anytime.

Terraform State Explained: Remote Backends, Locking and Fixing Drift, DevOps Society