DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 8 of 17
Your progress · 0%
On this page
  1. Why state exists
  2. What state is
  3. Remote state and locking
  4. Moving and importing
  5. State best practices
↖ Course roadmap
Lesson 8 · State

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.

35 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 5 complete
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.
Code walkthrough: the S3 backend block: explained, not run.
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.

Without a record, Terraform can't tell its resources from everyone else's.© Animation: DevOps Academy

Without a record, Terraform can't tell its resources from everyone else's.© Animation: DevOps Academy

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.

State is the link between an address in your code and a real object in the world.© Animation: DevOps Academy

State is the link between an address in your code and a real object in the world.© Animation: DevOps Academy

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.

Two copies of state and two applies at once: duplicates, or one change undoing another.© Animation: DevOps Academy

Two copies of state and two applies at once: duplicates, or one change undoing another.© Animation: DevOps Academy

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.

One shared state, one writer at a time.© Animation: DevOps Academy

One shared state, one writer at a time.© Animation: DevOps Academy

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

Complete Terraform Course - From BEGINNER to PRO!DevOps Directive · Watch on YouTube ↗

What state is

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

{
  "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:

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
}
$ 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
terraform state list
  • terraforminfrastructure as code
ls -ld out out/web.txt
  • lslist files

(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:

# 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:

$ 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.
terraform plan
  • terraforminfrastructure as code
  • planpreview changes

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:

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
}
$ 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.
terraform plan
  • terraforminfrastructure as code
  • planpreview changes

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:

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

resource "random_integer" "app_port" {
  min = 8000
  max = 8999
}
$ 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.
terraform plan
  • terraforminfrastructure as code
  • planpreview changes
terraform apply -auto-approve
  • applymake the changes
  • -auto-approveskip the yes prompt

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:

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:

$ terraform state rm random_integer.app_port
Removed random_integer.app_port
Successfully removed 1 resource instance(s).
terraform state rm random_integer.app_port
  • terraforminfrastructure as code

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.

⌘
Mini 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.

Input: A test project with the local and random providersOutput: ~/state-notes.txt
Reveal one safe solution
$ 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
terraform plan -no-color | grep -E 'has moved|imported|Plan:|No changes' >> ~/state-notes.txt
  • terraforminfrastructure as code
  • planpreview changes
  • |pipe: send output to the next command
  • grepfind lines that match a pattern
  • >>append output to a file
terraform apply -auto-approve
  • applymake the changes
  • -auto-approveskip the yes prompt

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 yourself

0 of 6 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 5

Why does Terraform need a state file?

Go deeper

Official reading for this lesson

  • DocsState overviewHashiCorp ↗
  • DocsS3 backend (with use_lockfile)HashiCorp ↗
  • DocsState lockingHashiCorp ↗
  • DocsRefactoring with moved blocksHashiCorp ↗
  • DocsImport blocksHashiCorp ↗
  • DocsRemoving resources (removed block)HashiCorp ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← Previousfmt, validate and TFLintNext lesson →Plan, apply and destroy