Terraform state explained backends and locking

Terraform State Explained: Backends, Locking and Workspaces

Introduction

Terraform state is the file that makes Terraform work — and the file that causes most Terraform disasters. It is the map between your configuration and the real infrastructure: without it, Terraform does not know what it already created. This article explains what state is, why keeping it on your laptop breaks the moment a second person joins, and how remote backends, locking and workspaces keep a team safe. It follows our Terraform Tutorial for Beginners, which built the first resources; this is the article that explains what happened under the hood.

Version note (26 Nov 2026): the current Terraform release is 1.17.2 (11 November 2026). The S3 backend examples below use the current native locking mechanism. If you are reading an older guide that configures a DynamoDB table for locking, that is the older pattern — it still works, but it is no longer the recommended one.

What State Is, and Why Terraform Needs It

Terraform is declarative: you describe the infrastructure you want, and Terraform works out how to get there. To do that it needs to know three things — what you want (the configuration), what actually exists (the real infrastructure), and what it created last time (the state). State is the third one: a JSON file, terraform.tfstate, that records every resource Terraform manages, with its real-world ID and its attributes.

When you run terraform plan, Terraform reads the configuration, reads the state, and then refreshes the state against the real infrastructure to find drift — resources changed outside Terraform. The plan is the difference between the refreshed state and the configuration. When you run terraform apply, Terraform creates, updates or destroys resources, then writes the new state. That is the whole cycle, and every Terraform concept that follows is a consequence of it: state is why Terraform can be incremental, and state is why a lost or corrupted state file is a serious incident.

A state file is not a secret, but it is sensitive. It can contain passwords, keys and other values from your resources — a database password stored in state is stored in plain text. Treat state files like credentials: never commit them to Git, never email them, and never store them unencrypted.

Local State: Fine for Learning, Wrong for Teams

By default Terraform stores state in a file next to your configuration. That is fine for a tutorial on your own laptop and wrong for everything else, for three reasons. First, nobody else can see it — a teammate running terraform plan on their machine starts from an empty state and plans to create everything again. Second, there is no locking — two people applying at the same time can write over each other’s state and corrupt it. Third, there is no backup — delete the file and Terraform forgets every resource it manages, which means the next apply tries to create duplicates, and the real infrastructure becomes orphaned.

The rule is simple: local state for learning, remote state for anything shared. The migration is one configuration block, and it is worth doing the first time a second person touches the project — not after the first incident.

Remote Backends: State in S3

A backend is where Terraform stores state. The most common backend for AWS teams is S3, and a backend block looks like this:

terraform {
  backend "s3" {
    bucket       = "my-terraform-state"
    key          = "network/terraform.tfstate"
    region       = "eu-west-2"
    use_lockfile = true
    encrypt      = true
  }
}

Four details matter. The bucket holds the state files; one bucket can hold many states, separated by key, so each project or environment gets its own key path. encrypt = true turns on server-side encryption, which is non-negotiable for a file that may contain secrets. use_lockfile = true enables native S3 locking — Terraform writes a lock file into the bucket while an apply is running, and a second apply waits or fails instead of corrupting the state. And the bucket itself should have versioning enabled, so a corrupted or overwritten state file can be restored from a previous version — the single cheapest insurance in all of Terraform.

Run terraform init after adding the backend block and Terraform migrates the local state into S3, asking first. From then on, every plan and apply reads and writes the state in S3, and every teammate with access to the bucket sees the same state. Other clouds have their equivalents — Azure Storage and Google Cloud Storage backends work the same way — and Terraform Cloud and HCP Terraform provide a managed backend with a web interface on top.

Locking: Why Two Applies Must Never Run Together

State corruption has one classic cause: two Terraform processes writing state at the same time. Without locking, both read the same state, both make changes, and the second one to write overwrites the first — leaving the state file describing only half of what was actually created. The resources from the first apply still exist in the cloud; Terraform simply no longer knows about them, and they become orphans that only a manual cleanup finds.

Locking prevents that. When an apply starts, Terraform acquires a lock; while the lock is held, any other plan or apply against the same state fails with a clear error naming the lock holder. The lock is released when the apply finishes — or when the process is killed, in which case the lock can be left behind and must be removed deliberately with terraform force-unlock, using the lock ID from the error message. Never force-unlock while an apply might still be running; the lock is there for a reason, and removing it mid-apply is how corruption happens.

The history matters for interviews: use_lockfile was introduced in Terraform 1.10 (November 2024) and became generally available in 1.11 (27 February 2025), when the DynamoDB arguments were deprecated. Before 1.10, S3 locking needed a separate DynamoDB table (dynamodb_table in the backend block). Since then, S3 native locking with use_lockfile = true is the recommended approach, and the DynamoDB table is the legacy pattern. An interviewer who asks about DynamoDB locking is testing whether your knowledge is current — mention both, and say which one you would use today.

Workspaces vs Modules vs Separate Configurations

Terraform workspaces let one configuration manage several environments — typically default, dev, staging and production — with a separate state file per workspace in the same backend. Switch with terraform workspace select staging, and the same code deploys to a different state. Workspaces are best when the environments are nearly identical and differ only in a few variables, such as instance size or replica count.

They are the wrong tool when environments genuinely differ. If production has a multi-AZ database and dev has a single small one, or if different teams own different environments, separate configurations — or the same module called with different inputs — are clearer. The interview answer is the trade-off: workspaces are cheap and simple, but they share one codebase and one blast radius; separate configurations cost duplication and gain isolation. Most mature teams end up with modules plus one configuration per environment, and workspaces reserved for short-lived environments such as per-developer sandboxes.

The State Commands You Will Actually Use

State is a file, and Terraform gives you tools to inspect and repair it — but every one of these commands edits the map, not the territory, so use them deliberately and back the state up first.

  • terraform state list — every resource in the state. Start here whenever you inherit a project.
  • terraform state show <address> — the full attributes of one resource, including the ones Terraform will not print in a plan.
  • terraform state mv <old> <new> — rename a resource in state when you refactor the configuration, so Terraform does not destroy and recreate it.
  • terraform state rm <address> — stop managing a resource without destroying it. The resource keeps running in the cloud; Terraform simply forgets it. The usual use is handing a resource to another configuration.
  • terraform import <address> <real-id> — adopt a resource that was created outside Terraform, such as in the console, into state. Run terraform plan immediately afterwards and expect a diff — the configuration must then be written to match the real resource.
  • terraform refresh — update the state from the real infrastructure without changing anything. It is deprecated: use terraform plan -refresh-only or terraform apply -refresh-only instead. Modern Terraform refreshes automatically during plan, so this is rarely run directly.

The golden rule: state commands change Terraform’s memory, not the cloud. If you remove a resource from state and then run apply, Terraform will try to create it again — because as far as it knows, the resource does not exist. That is the correct behaviour, and the reason every state operation deserves a backup first: copy the state file, or rely on S3 versioning, before you touch it.

Drift, Secrets and Common Disasters

Drift is when the real infrastructure changes outside Terraform — someone edits a security group in the console, or a cloud provider changes a default. Terraform detects drift on the next plan and proposes to revert it, which is usually right and occasionally destructive if the manual change was intentional. The discipline is to make all changes through Terraform, and to treat the console as read-only for managed resources.

Secrets in state are the quiet risk. Any sensitive value Terraform manages — a database password, a private key — is stored in the state file in plain text. Remote state in an encrypted, access-controlled S3 bucket is the mitigation, plus marking variables as sensitive = true so they do not appear in plan output, and using a secrets manager for the values themselves rather than generating them in Terraform.

The three classic disasters are all state disasters: a deleted state file with no backup (orphaned infrastructure), two applies running without locking (corrupted state), and a state file committed to a public Git repository (leaked secrets). Every one of them is prevented by the practices in this article — remote backend, versioning, encryption, locking — which is why interviewers treat state as a proxy for whether you have run Terraform with a team or only on your own laptop.

FAQ

Should I ever edit the state file by hand? Only as a last resort, and only on a copy, with the original backed up. The state commands exist precisely so you do not have to. If you find yourself editing JSON directly, stop and check whether terraform state mv, rm or import does what you need.

What happens if I lose the state file? Terraform forgets everything it manages. The infrastructure keeps running, but the next apply will try to create it all again — and fail on duplicate names, or worse, succeed and leave you with two of everything. Recovery means importing each resource back into a new state file, which is slow and error-prone. That is why the S3 bucket holding state has versioning enabled before anything else.

Do I need a separate backend per environment? No — one bucket, one key per environment or project, is the normal pattern. Separate buckets are for separate AWS accounts or separate teams, where access control is the reason.

How does state work in a CI/CD pipeline? The pipeline runs Terraform with credentials that can read and write the backend, and locking is what makes it safe: if two pipelines trigger at once, one waits. Our Jenkins CI/CD Pipeline Tutorial shows the pipeline shape; the Terraform step inside it is terraform init, plan, and apply with the remote backend already configured.

Conclusion

State is the least glamorous part of Terraform and the part that matters most in a team. Local state is fine for a tutorial; a remote backend with encryption, versioning and locking is the minimum for real work. Learn the state commands, respect the lock, and never commit a state file to Git — and when an interviewer asks about state, you will be answering from the place where Terraform actually breaks in production, which is exactly what they want to hear.

—

—

Scroll to Top