# State: Terraform's memory

What the state file is and why Terraform needs it, how teams share it safely with a remote backend and locking, and how to rename, import and forget resources without breaking anything.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 8. About 35 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/08-state

## What you will learn

- Explain what the state file records and why Terraform can't work without it
- Read state with terraform state list and state show
- Configure a remote S3 backend with locking, and explain what a lock protects against
- Rename resources with moved blocks and adopt existing ones with import blocks
- Follow the rules that keep state safe

> **Lab status.** **Verified lab:** state list and show, the state-lock clash, moved, import (and the import that's not supported) and state rm. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the S3 backend block: explained, not run. <br />**Cloud lab:** an S3 backend needs an AWS account and a bucket.

## Why state exists

State is the part of Terraform that surprises people most, and the part that causes the worst
incidents when it's handled badly. It's worth seeing the problem one step at a time.

### The problem: code alone doesn't know what it owns

Your code says `resource "aws_instance" "web"`. The AWS account has three running instances: one
made in the console last year, one from another team, one left over from a test. Which one is
"web"? If Terraform guessed, it could modify or delete someone else's server.

> **Figure.** Animated. A config with resource aws_instance web on the left. An AWS account on the right with three running instances: i-0a1f made in the console, i-07c2 from another team, and i-0d93 an old test. Question marks appear under each: which one did this config create?
>
> Without a record, Terraform can't tell its resources from everyone else's.

### The fix: a state file maps addresses to real IDs

After every apply, Terraform writes down each resource address and the real object it created:
`aws_instance.web` is `i-07c2`, with all its attributes. Next time, it only looks at `i-07c2`, and
the other instances are never touched.

> **Figure.** Animated. A state file appears between the config and the cloud, mapping aws_instance.web to id i-07c2 with instance_type t3.micro. A line connects the config through the state to i-07c2, marked managed by this config. The other two instances are marked not ours, ignored.
>
> State is the link between an address in your code and a real object in the world.

### The new problem: a file on a laptop breaks in a team

By default the state is `terraform.tfstate` on whoever ran apply. A teammate with an old copy, or
none, runs apply at the same time, and Terraform happily creates a second server, because their
state says there isn't one.

> **Figure.** Animated. Asha's laptop has state saying web is i-07c2. Ravi's laptop has an old, empty copy. Both run terraform apply. The account ends up with web i-07c2 and a duplicate web i-0b88.
>
> Two copies of state and two applies at once: duplicates, or one change undoing another.

### The fix for teams: remote state with a lock

The state moves to one shared place, such as an S3 bucket, and every run takes a **lock** first. Only
one writer at a time; everyone else waits.

> **Figure.** Animated. Both laptops point at one state file, shop/prod/terraform.tfstate, in a versioned and encrypted S3 bucket. Asha runs apply and the state shows locked by asha. Ravi runs plan and gets Error acquiring the state lock until her apply finishes.
>
> One shared state, one writer at a time.

In this lesson you'll look inside real state, hit a real lock, and learn the safe ways to rename,
import and forget resources.

> **Video.** [Complete Terraform Course - From BEGINNER to PRO!](https://www.youtube.com/watch?v=7xngnjfIlK4) (DevOps Directive)

## What state is

The state file is JSON. Here's the start of the lab's, after creating one file:

```json
{
  "version": 4,
  "terraform_version": "1.17.1",
  "serial": 1,
  "lineage": "967442eb-1a4e-b21a-d36f-7667ac820f19",
  "outputs": {},
  "resources": [
    {
      "mode": "managed",
      "type": "local_file",
      "name": "web",
      "provider": "provider[\"registry.terraform.io/hashicorp/local\"]",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "content": "web server\n",
```

- **`serial`** goes up on every change, so Terraform can refuse to overwrite newer state with older.
- **`lineage`** is a unique ID for this state's history, so you can't accidentally push a completely
  different project's state over it.
- **`resources`** lists every managed object with its type, name, provider and all its attributes.

Never edit it by hand. Use the commands, which read it for you. The resource behind this state sets
safe permissions explicitly, instead of taking the provider's default:

```hcl
resource "local_file" "web" {
  filename             = "${path.module}/out/web.txt"
  content              = "web server\n"
  file_permission      = "0600" # owner read/write only
  directory_permission = "0700" # owner only
}
```

```sh
$ terraform state list
local_file.web
$ terraform state show local_file.web
# local_file.web:
resource "local_file" "web" {
    content              = <<-EOT
        web server
    EOT
    ...
    directory_permission = "0700"
    file_permission      = "0600"
    filename             = "./out/web.txt"
    id                   = "b98caeeaab8b12bc7123853e05f2dfcc547c6ecd"
}
$ ls -ld out out/web.txt
drwx------ out
-rw------- out/web.txt
```

(The `...` hides six checksum attributes of the content.) `state show` prints what Terraform recorded;
`ls` confirms the real file matches: only the owner can read it.

Besides the ID mapping, state caches attributes (so plan can compare without asking for everything
again) and remembers dependencies (so destroy happens in the right order even after you delete the
code).

> **Why set permissions explicitly.** Left unset, `local_file` creates files and folders with `0777`: anyone on the machine can read and change them. That default appears in some plan output in lesson 9. Don't rely on it. Set `file_permission = "0644"` for ordinary files and `"0600"` (with `directory_permission = "0700"`) for anything private. For secrets, `local_sensitive_file` defaults to `0700`, as the Security lesson shows. The same thinking applies to `terraform.tfstate` itself on a laptop: keep it readable only by you, and better, keep it in a remote backend.

## Remote state and locking

A **backend** decides where state lives. For AWS teams the usual choice is S3:

```hcl
# backend.tf
terraform {
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "shop/prod/terraform.tfstate"
    region       = "ap-south-1"
    encrypt      = true
    use_lockfile = true # lock with a .tflock object in the same bucket
  }
}
```

What each setting does:

- **`bucket` and `key`**: where the file goes. One bucket holds many states; the key separates them
  (`shop/prod/...`, `shop/dev/...`).
- **`encrypt`**: server-side encryption, because state holds secrets.
- **`use_lockfile`**: native S3 locking, available since Terraform 1.10. Older setups used a DynamoDB
  table (`dynamodb_table`), which is now deprecated.

Create the bucket once, outside this configuration, with versioning on (so you can roll back a
corrupted state) and public access blocked. Then run `terraform init`, and with existing local state,
`terraform init -migrate-state` copies it up. Other good backends: HCP Terraform, Azure Storage
(`azurerm`), Google Cloud Storage (`gcs`).

### A real lock

Every backend that supports it locks during writes; even the local backend does. In the lab, one
terminal ran an apply that takes 12 seconds, and a second terminal ran plan meanwhile:

```text
$ terraform plan

Error: Error acquiring the state lock

Error message: resource temporarily unavailable
Lock Info:
  ID:        8da76c6d-c1c4-4393-d885-86b285980ed6
  Path:      terraform.tfstate
  Operation: OperationTypeApply
  Who:       rajeev@Elonerajeev
  Version:   1.17.1
  Created:   2026-11-08 15:39:00.604349637 +0000 UTC
  Info:

Terraform acquires a state lock to protect the state from being written
by multiple users at the same time. Please resolve the issue above and try
again. For most commands, you can disable locking with the "-lock=false"
flag, but this is not recommended.
```

The lock says who holds it, for which operation and since when. Wait for it. If a run crashed and
left a stale lock, and you're **sure** nothing is running, release it with
`terraform force-unlock 8da76c6d-c1c4-4393-d885-86b285980ed6`. Never use `-lock=false` on shared
state.

## Moving and importing

Code changes over time, and state has to follow without destroying anything real.

### Rename with a moved block

Renaming `local_file.web` to `local_file.frontend` looks, to Terraform, like "destroy web, create
frontend". A `moved` block says it's the same object:

```hcl
resource "local_file" "frontend" {
  filename             = "${path.module}/out/web.txt"
  content              = "web server\n"
  file_permission      = "0600"
  directory_permission = "0700"
}

moved {
  from = local_file.web
  to   = local_file.frontend
}
```

```text
$ terraform plan
local_file.frontend: Refreshing state... [id=b98caeeaab8b12bc7123853e05f2dfcc547c6ecd]

Terraform will perform the following actions:

  # local_file.web has moved to local_file.frontend
    resource "local_file" "frontend" {
        id                   = "b98caeeaab8b12bc7123853e05f2dfcc547c6ecd"
        # (10 unchanged attributes hidden)
    }

Plan: 0 to add, 0 to change, 0 to destroy.
```

Same ID, nothing created or destroyed. Moved blocks also handle moving a resource into a module
(`to = module.site.local_file.page`). The older command `terraform state mv` does the same thing
directly on state, but a `moved` block is reviewed in a pull request and works for everyone who runs
the code. Keep moved blocks for a while, so every environment picks them up.

### Adopt existing resources with an import block

Something was created by hand and you want Terraform to manage it. Write the resource, and an
`import` block with its real ID. The lab imported a port number another team had already chosen:

```hcl
import {
  to = random_integer.app_port
  id = "8443,8000,8999"
}

resource "random_integer" "app_port" {
  min = 8000
  max = 8999
}
```

```text
$ terraform plan
random_integer.app_port: Preparing import... [id=8443,8000,8999]
random_integer.app_port: Refreshing state... [id=8443]

Terraform will perform the following actions:

  # random_integer.app_port will be imported
    resource "random_integer" "app_port" {
        id     = "8443"
        max    = 8999
        min    = 8000
        result = 8443
    }

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
$ terraform apply -auto-approve
...
random_integer.app_port: Importing... [id=8443,8000,8999]
random_integer.app_port: Import complete [id=8443,8000,8999]

Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
```

The ID format is different for each resource type; the provider docs have an "Import" section at the
bottom of each page (for an EC2 instance it's the instance ID, `i-0abc...`). After import, a plan
should say "No changes": if it wants to change things, your code doesn't match reality yet. Two
helpers: `terraform plan -generate-config-out=generated.tf` writes the resource code for you, and not
every resource supports import at all. In the lab, `local_file` refused:

```text
Error: Resource Import Not Implemented

This resource does not support import. Please contact the provider developer
for additional information.
```

### Forget a resource

To stop managing something without deleting it, for example handing it to another team's
configuration:

```sh
$ terraform state rm random_integer.app_port
Removed random_integer.app_port
Successfully removed 1 resource instance(s).
```

The real object keeps running. In code, a `removed` block with `lifecycle { destroy = false }` does
the same and gets reviewed like any other change.

## State best practices

1. **Never commit state to Git.** It can contain passwords and keys in plain text, and Git can't lock.
2. **Use a remote backend with locking, encryption and versioning** for anything shared.
3. **Restrict who can read the state bucket.** Reading state means reading every secret in it.
4. **One state per environment and per area.** A small state plans faster and limits the damage of a
   mistake (lesson 15).
5. **Change state with code** (`moved`, `import`, `removed` blocks) rather than ad-hoc `state`
   commands, so changes are reviewed.
6. **Never edit the JSON by hand.** If you must, `terraform state pull > backup.tfstate` first.

> **Losing state is worse than losing code.** If the state is lost, Terraform forgets everything it manages. The next apply tries to create it all again, and fails or makes duplicates. Bucket versioning is your undo button. Turn it on before the first apply.

## Mission: Rename, import and forget, without breaking anything

In a test project, apply one local_file, rename it with a moved block, import a random_integer with an import block, then state rm it. After each step, run terraform plan and confirm it says 0 to add, 0 to change, 0 to destroy (or 1 to import). Record each plan's summary line.

- You need: A test project with the local and random providers
- You'll have: ~/state-notes.txt

```sh
$ terraform plan -no-color | grep -E 'has moved|imported|Plan:|No changes' >> ~/state-notes.txt
$ terraform apply -auto-approve
$ terraform state list >> ~/state-notes.txt
$ terraform state rm random_integer.app_port >> ~/state-notes.txt
```

In the lab, the rename planned `0 to add, 0 to change, 0 to destroy` and the import `1 to import`.
If the rename shows `1 to add` and `1 to destroy`, the moved block's `from` doesn't match the old
address exactly.

## Try it

- Apply a small project, then run `terraform state list` and `terraform state show <address>`.
- Open terraform.tfstate in a text editor and find the resource's ID.
- Start a slow apply and run `terraform plan` in a second terminal to see the lock error.
- Rename a resource and add a moved block, then confirm the plan says "has moved".
- Import an existing value with an import block.
- Do the mini mission and keep `~/state-notes.txt`.

## Quiz

1. Why does Terraform need a state file?
   - To store your .tf code
   - **To map each resource address in your code to the real object it created, and remember its attributes** (answer)
   - To keep provider downloads
   Why: Without state, Terraform couldn't tell which real objects belong to your configuration, so it couldn't update or delete them safely.

2. Two people run terraform apply at the same time against the same remote state with locking. What happens?
   - Both apply and the state merges
   - **The second one fails with "Error acquiring the state lock" until the first finishes** (answer)
   - The second one overwrites the first
   Why: The lock allows one writer at a time. Without it, two applies could create duplicates or overwrite each other's state.

3. You renamed `local_file.web` to `local_file.frontend`. How do you avoid Terraform destroying and recreating it?
   - Delete the state file
   - **Add a moved block from local_file.web to local_file.frontend** (answer)
   - Run terraform destroy first
   Why: A moved block tells Terraform the object just has a new address. The plan shows "has moved" and changes nothing real.

4. What does terraform state rm do?
   - Deletes the real resource
   - **Makes Terraform forget a resource, leaving the real object running** (answer)
   - Removes the state file
   Why: state rm only edits state. The real object keeps running unmanaged; in code, a removed block does the same job and gets reviewed.

5. Should terraform.tfstate be committed to Git?
   - Yes, so the team shares it
   - **No. It can hold secrets in plain text and can't be locked in Git; use a remote backend** (answer)
   - Only for production
   Why: Remote backends give a single shared copy, locking, versioning and encryption. Git gives none of those.

## Resources

- [State overview](https://developer.hashicorp.com/terraform/language/state) (HashiCorp)
- [S3 backend (with use_lockfile)](https://developer.hashicorp.com/terraform/language/backend/s3) (HashiCorp)
- [State locking](https://developer.hashicorp.com/terraform/language/state/locking) (HashiCorp)
- [Refactoring with moved blocks](https://developer.hashicorp.com/terraform/language/modules/develop/refactoring) (HashiCorp)
- [Import blocks](https://developer.hashicorp.com/terraform/language/import) (HashiCorp)
- [Removing resources (removed block)](https://developer.hashicorp.com/terraform/language/resources/syntax#removing-resources) (HashiCorp)
