29 November 2026 · 12 min read · Download as PDF

Terraform state explained: commands, import and moved blocks, S3 locking and HCP Terraform

Terraform state ties your code to the real objects it manages. The commands to inspect and change it, import, moved and removed blocks, an S3 backend with native locking (no DynamoDB), HCP Terraform, secrets in state, the edge cases and an FAQ.

Cover: Terraform state explained: commands, import and moved blocks, S3 locking and HCP Terraform

Terraform state is the record that ties each resource block in your code to the real object it created, such as aws_instance.web to instance i-0abc…. Terraform reads it on every plan and writes it on every apply, so whoever controls the state controls what Terraform thinks exists. This article goes with our video lesson State: Terraform's memory, which explains in under four minutes what state is, how plan compares configuration, state and the real world, and why a team needs one shared, locked copy. Here is what the video can't hold: the commands to copy, the blocks that replace hand edits (import, moved, removed), a remote backend on Amazon Simple Storage Service (S3) with native locking, HashiCorp Cloud Platform (HCP) Terraform, the edge cases, an FAQ and every source.

TL;DR

  • Never edit terraform.tfstate by hand. Read it with terraform state list, state show and show -json; change it with moved, removed and import blocks, which show up in a plan you can review. The terraform state mv and state rm commands still work, but change state immediately with no plan.
  • On Amazon S3 (Simple Storage Service), lock with use_lockfile = true. S3 native locking has been generally available since Terraform 1.11 (27 Feb 2025). The DynamoDB lock table is deprecated, still accepted in Terraform 1.17.2, and due to be removed "in a future minor version".
  • Turn on bucket versioning. HashiCorp "highly recommends" it so you can recover an older state.
  • sensitive = true does not keep a secret out of state. It only hides it in output. Ephemeral values (Terraform 1.10+) and write-only arguments (1.11+) are left out of state entirely.
  • HCP Terraform (on the HashiCorp Cloud Platform) stores, locks and versions state for you, encrypts it at rest, and is free up to 500 managed resources.

The state commands, to copy

These work whether your state is local or in a remote backend. The one difference is force-unlock: a local state file can't be unlocked by another process, so it is for backends that hold a lock you can release. Where a command needs a recent Terraform, the row says so.

Task

Command

Changes state?

List every resource Terraform manages

terraform state list

No

List only some (resource-address pattern)

terraform state list module.network

No

Every attribute of one resource

terraform state show 'aws_instance.web[0]'

No

The same, as JSON for scripts (Terraform 1.16+)

terraform state show -json aws_instance.web

No

The whole state, readable or as JSON

terraform show / terraform show -json

No

Download the raw state (back it up first)

terraform state pull > backup.tfstate

No

Rename an address, keep the object

terraform state mv aws_instance.a aws_instance.b

Yes, at once

Forget an object, leave it running

terraform state rm aws_s3_bucket.logs

Yes, at once

Point resources at a different provider source (a fork, a moved namespace)

terraform state replace-provider OLD_SOURCE NEW_SOURCE

Yes, at once

Accept changes made outside Terraform

terraform apply -refresh-only

Yes, after you approve

Rebuild one degraded object (replaces taint)

terraform apply -replace=aws_instance.web

Yes, after you approve

Release your own stuck lock

terraform force-unlock LOCK_ID

Lock only

Upload a repaired state (last resort)

terraform state push fixed.tfstate

Yes

Quote addresses that contain brackets, as in 'aws_instance.web[0]', or your shell may expand them. Add -dry-run to mv or rm first: it lists the instances that match without changing anything. Treat any -json output as secret: it can include sensitive attribute values in plain text. terraform refresh still exists but is deprecated; it is apply -refresh-only -auto-approve without the chance to review.

The state triangle. Top left, Configuration: what you want. Top right, Real world: what exists. At the bottom, State: what Terraform knows, one entry per resource. An arrow from configuration to the real world reads apply makes it so; an arrow between state and the real world reads refresh reads the real world. In the middle, a label reads Plan compares all three.

The state triangle from the lesson. Read it with the table above: state list and state show read the bottom corner, -refresh-only copies the right-hand corner into it, and moved, removed and import change how the left-hand corner maps onto it. Open this diagram in archhy.

Change state through a plan, not by hand

Since Terraform 1.1 you can describe a state change in code. The change appears in terraform plan, goes through code review with everything else, and runs on apply. That beats a teammate running state mv on their laptop while someone else's pipeline plans against the old address, which the state mv docs warn can destroy and recreate the object.

You want to

Block (reviewed in a plan)

Since

Old command (immediate)

Rename a resource or move it into a module

moved

1.1

terraform state mv

Stop managing something, but keep it

removed with destroy = false

1.7

terraform state rm

Adopt something built outside Terraform

import

1.5

terraform import

Adopt many at once

import with for_each

1.7

One command per resource

Rename without destroying: moved

Text
# You renamed resource "aws_instance" "a" to "web".moved {  from = aws_instance.a  to   = aws_instance.web}# You moved a bucket into a module.moved {  from = aws_s3_bucket.assets  to   = module.storage.aws_s3_bucket.assets}

Without the block, Terraform reads a rename as "destroy the old one, create a new one". With it, the plan shows the object being moved and nothing replaced. If you publish a module, leave old moved blocks in place: HashiCorp calls removing one "a breaking change" for anyone still on the old address.

Let go without destroying: removed

Text
# Delete the resource block, and add:removed {  from = aws_s3_bucket.legacy_logs  lifecycle {    destroy = false  }}

Watch the default. A removed block without destroy = false destroys the real object as well as removing it from state. Use destroy = false when another team or tool is taking the resource over.

Adopt existing infrastructure: import

Text
import {  to = aws_s3_bucket.assets  id = "example-assets-bucket"}# Several at once (Terraform 1.7+)import {  for_each = toset(["example-logs", "example-backups"])  to       = aws_s3_bucket.kept[each.key]  id       = each.key}

Write the matching resource block yourself, or let Terraform draft it for resources the provider can import:

Text
terraform plan -generate-config-out=generated.tf

The output file must not exist yet, and HashiCorp still labels configuration generation experimental, so read generated.tf before you commit it. For resources with complex schemas the draft can be invalid (two arguments that conflict, for example): fix it and plan again. The id must be known at plan time. Since Terraform 1.12 some resources can be imported by an identity (a set of attributes such as account, bucket and Region) instead of an id, if the provider supports it. To find candidates in bulk, Terraform 1.14 added terraform query with list blocks in *.tfquery.hcl files, which can generate the import configuration for you.

Whichever way you import, keep one rule: one real object, one address. Importing the same bucket into two resource blocks leaves Terraform with two owners for one object, and the docs warn it "may behave unexpectedly".

A remote backend on Amazon S3, with native locking

State on a laptop, or state the team shares. On the left, On a laptop: one file, on one disk; nobody else can see it; two laptops, two truths. An arrow leads to the right, Remote backend: one shared state, locked during a run, every version kept. Below, examples of remote backends: HCP Terraform, Amazon S3, Azure Blob Storage, Google Cloud Storage, and more. A banner reads Shared, locked, versioned.

From laptop to shared backend. "Every version kept" holds for HCP Terraform, and for S3 only once you turn on bucket versioning. Open this diagram in archhy.

The bucket must exist before Terraform can use it, so create it separately (by hand, or in a small bootstrap configuration with local state) and turn on versioning. Then:

Text
terraform {  backend "s3" {    bucket       = "example-tfstate"    key          = "network/terraform.tfstate"    region       = "us-east-1"    use_lockfile = true   # S3 native locking; the default is false    encrypt      = true   # server-side encryption of state and lock files  }}

Then run terraform init -migrate-state to copy your local state into the bucket. (-reconfigure switches backend without copying, which is rarely what you want for an existing project.) While a run holds the lock, a lock file sits next to the state at the same key plus .tflock, here network/terraform.tfstate.tflock.

Things the S3 example doesn't show

  • Locking is off unless you ask. The S3 backend's locking is opt-in: with neither use_lockfile nor the deprecated dynamodb_table, there is no lock.
  • IAM (Identity and Access Management) permissions. Besides s3:ListBucket on the bucket and read and write on the state key, the role needs s3:GetObject, s3:PutObject and s3:DeleteObject on the .tflock key. With kms_key_id, add kms:Encrypt, kms:Decrypt and kms:GenerateDataKey on the AWS Key Management Service (KMS) key. These are the default workspace's keys; with command-line interface (CLI) workspaces, grant the same on the env:/<workspace>/… keys too (see the last point).
  • No variables in the backend block. It can't refer to variables, locals or data sources. To vary it per environment, leave values out (backend "s3" {}) and pass them at terraform init -backend-config=prod.s3.tfbackend, a "partial configuration".
  • Keep credentials out of it. Anything you put in the backend block or -backend-config is written in plain text to .terraform/terraform.tfstate and into plan files. Use your usual AWS environment variables or profile.
  • CLI workspaces share the bucket. A workspace called dev stores its state at env:/dev/network/terraform.tfstate (change the prefix with workspace_key_prefix). HashiCorp says CLI workspaces are not for environments that need separate credentials and access controls; use separate backends or HCP Terraform workspaces for those.

Moving off the DynamoDB lock table

Terraform 1.10 (27 Nov 2024) added S3 native locking, and 1.11 (27 Feb 2025) made it generally available and deprecated the DynamoDB arguments. You can set both while you migrate; Terraform then takes the lock from both. So: add use_lockfile = true next to dynamodb_table, run terraform init -reconfigure (the state stays where it is), make sure everyone's Terraform is 1.11 or later, then remove dynamodb_table, run terraform init -reconfigure again in every working directory and pipeline, and only then delete the table. As of Terraform 1.17.2 the DynamoDB arguments still work, flagged deprecated.

Which backend?

Backend

Locking

History kept

Good for

local (default)

Yes, on one machine

One previous snapshot, terraform.tfstate.backup

Learning, one person

s3

Opt-in: use_lockfile = true

If bucket versioning is on

AWS teams running Terraform in their own CI (continuous integration)

azurerm

Yes, Blob Storage native

Through storage settings

Azure teams

gcs

Yes

If object versioning is on

Google Cloud teams

HCP Terraform (cloud block)

Yes, plus a run queue per workspace

Every state version, with diffs

Teams that want runs, state and permissions in one place

You can't add your own backend type as a plugin: Terraform ships with a fixed set. And don't keep state in Git. HashiCorp warns against any storage "that does not support Terraform state locking and secure access control".

HCP Terraform: state you don't have to look after

Instead of a backend block, you add a cloud block (Terraform 1.1+). A configuration can have one or the other, not both.

Text
terraform {  cloud {    organization = "example-org"    workspaces {      name = "network-prod"    }  }}

Run terraform login, then terraform init, and the workspace holds the state. You also get:

  • Every state version, each linked to its run and commit, with a diff against the one before, on the workspace's States tab.
  • Encryption at rest, and TLS (Transport Layer Security) in transit.
  • A workspace lock you can set on purpose (say, during an incident), which stops all applies and most plans, whether they come from the UI, the CLI (command-line interface), the API or automation, and blocks state uploads by anyone but the user who locked it. Admins can force-unlock another user's lock.
  • Safer sharing. To read another workspace's outputs, HashiCorp recommends the tfe_outputs data source over terraform_remote_state, because the latter needs access to the whole state snapshot, secrets and all.

The Free plan covers up to 500 managed resources. Each resource instance in state counts, including every count and for_each copy and those inside modules; data sources don't.

A remote run in HCP Terraform. On the left, a developer at a terminal (CLI: terraform apply) and a CI pipeline (API-driven run) both send runs into an HCP Terraform workspace. Inside it, a run queue takes one run at a time and passes the next run to a single-use run VM. An arrow labeled read, lock, write joins the VM to the workspace's state, where every version is kept; the VM also makes provider API calls into an AWS account, creating servers and buckets.

Where state sits in an HCP Terraform run: HCP Terraform queues runs one at a time and locks the workspace for the run, and the single-use VM (virtual machine) reads and writes the workspace's state under that lock. Open this diagram in archhy. The lesson Remote state and where runs happen walks through it.

Secrets in state: what actually keeps them out

State is plain JSON (JavaScript Object Notation). An initial database password set through Terraform is in it, readable by anyone who can read the state.

Setting

Hidden in plan and apply output?

Kept out of state?

Needs

sensitive = true on a variable or output

Yes

No

Terraform 0.15+

ephemeral = true on a variable or child-module output; ephemeral blocks

Add sensitive too

Yes

Terraform 1.10+

A write-only argument on a resource

Yes

Yes

Terraform 1.11+, and a provider that offers one

Two traps: terraform output -json and -raw print sensitive outputs in plain text, and so does terraform show -json. Keep those out of CI logs. Saved plan files (terraform plan -out) hold sensitive values too, so store and delete them like state. If you use OpenTofu, the open-source fork, it can also encrypt state and plan files itself (since OpenTofu 1.7); lose the key and the state is unrecoverable.

Edge cases that catch people out

  • .terraform.lock.hcl is not the state lock. It is the dependency lock file, recording which provider versions you use. Commit it. The state lock is something else, held by the backend during a run.
  • state rm is not "delete". The object keeps running, unmanaged. The next plan offers to create it again, which may fail if the name is taken.
  • force-unlock needs the lock ID, which Terraform prints when it can't get or release a lock. Use it only for your own lock after a crash. Unlocking someone else's live run can mean two writers on one state. In CI, -lock-timeout=5m waits for a lock instead of failing.
  • state push has guards. It refuses a state with a different lineage (a different state altogether) or a lower serial (older than what's there). -force skips both; don't, unless you're restoring a backup on purpose.
  • Skipping refresh hides drift. -refresh=false, and the -minimal-refresh option added in Terraform 1.17, make plans faster but can miss changes made outside Terraform. Avoid them when upgrading providers.
  • Don't parse state files. The format can change between versions. Read terraform show -json or terraform output -json instead.
  • Locking can be switched off per command with -lock=false. HashiCorp: "we do not recommend it".

FAQ

What is Terraform state, in one line?

A JSON record mapping each resource address in your configuration to the real object's ID, plus dependencies and cached attributes, so Terraform can tell what to create, change or destroy.

Can Terraform work without state?

No. HashiCorp's own explanation: early prototypes used tags instead, but "not all resources support tags, and not all cloud providers support tags". State also remembers dependencies, so Terraform can delete resources you removed from the code in the right order.

Should I commit terraform.tfstate to Git?

No. It can hold secrets, and Git can't lock it. Add *.tfstate and *.tfstate.* to .gitignore, and do commit .terraform.lock.hcl.

Do I still need a DynamoDB table for S3 state locking?

No. Set use_lockfile = true (Terraform 1.11+ for the generally available version). The DynamoDB arguments are deprecated and will be removed in a future minor version.

How do I rename a resource without destroying it?

Add a moved block with the old and new addresses, then plan. The plan should show a move and no replacement.

How do I stop managing a resource but keep it?

Delete its resource block and add a removed block with lifecycle { destroy = false }. Without that line, Terraform destroys it.

terraform import command or import block?

The block. It's planned and reviewable, works with for_each, and can generate the configuration. The command still works and imports straight into state.

Where does HCP Terraform keep my state?

In the workspace, encrypted at rest, with every version kept. Remote runs use it automatically and ignore any backend block.

Does all this apply to OpenTofu?

The ideas and most of the commands do: OpenTofu keeps state the same way and also has import, moved and removed blocks. Check its documentation for backend details and its own state encryption.

Watch, then practice

The video lesson State: Terraform's memory is the short version, with the state triangle and the two-laptops problem. It is part of the free Terraform and Packer course, which goes on to remote state and HCP Terraform workspaces.

More from the blog