Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท State Management

State Commands: Move, Import, Remove and Replace

Refactor safely with Terraform state commands: state mv, moved blocks, import blocks, removed blocks and the -replace flag, with plans that show the effect.

Infrastructure code changes shape. You rename a resource, split a file into a module, adopt a server someone created by hand, or stop managing a bucket without deleting it. Because Terraform identifies resources by their address in state, a plain rename looks to Terraform like "destroy the old one, create a new one". The tools in this lesson tell Terraform "it is the same object" instead.

You will meet two generations of tools: imperative commands (terraform state mv, rm) and declarative blocks (moved, import, removed). Prefer the blocks: they live in code, are reviewed in pull requests and work the same for everyone.

The rename problem

Imagine you rename a resource:

HCL
# before
resource "aws_s3_bucket" "assets" { bucket = "acme-assets" }

# after
resource "aws_s3_bucket" "media" { bucket = "acme-assets" }

The plan (example output) would say:

TEXT
  # aws_s3_bucket.assets will be destroyed
  # aws_s3_bucket.media will be created

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

For a bucket full of files, that is a catastrophe. Tell Terraform about the rename instead.

moved blocks (preferred)

HCL
moved {
  from = aws_s3_bucket.assets
  to   = aws_s3_bucket.media
}

Now the plan says aws_s3_bucket.assets has moved to aws_s3_bucket.media with no destroy. The same block handles moving a resource into a module (to = module.storage.aws_s3_bucket.media), changing from a single resource to count (to = aws_instance.web[0]) and renaming a module call. Keep moved blocks in the code for a release or two, so every environment gets a chance to apply them, then remove them.

terraform state mv (imperative)

The older way changes the state directly, immediately:

Terminal
terraform state mv aws_s3_bucket.assets aws_s3_bucket.media
terraform state mv aws_instance.web module.compute.aws_instance.web

It is fast for one-offs, but nobody reviews it and other environments do not get it automatically. Always keep a backup (terraform state pull > backup.json) and run terraform plan right after; a correct move shows "No changes".

The next program is a stand-in that models address rewriting. It also warns when a rename would otherwise look like destroy + create.

Python Move addresses in a state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Importing existing resources

Terraform can only manage what is in its state. To adopt a resource created by hand, you import it. Write the resource block, then add an import block (Terraform 1.5+):

HCL
import {
  to = aws_s3_bucket.legacy
  id = "acme-legacy-bucket"
}

resource "aws_s3_bucket" "legacy" {
  bucket = "acme-legacy-bucket"
}

terraform plan now shows the resource as will be imported, and terraform apply records it in state. The id format differs per resource type and is documented on each resource's page under "Import" (a bucket takes its name, a security group its sg-... ID).

Terraform can even draft the code for you:

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

Review the generated file, trim defaults and read-only attributes, and move it into your configuration. From 1.7 an import block can also use for_each, to adopt many resources at once.

The classic command still works for single imports:

Terminal
terraform import aws_s3_bucket.legacy acme-legacy-bucket

After importing, run terraform plan until it reports no unexpected differences; the first plans often show attributes you must add to the code.

Removing from state without destroying

Sometimes you want Terraform to forget a resource but leave it running, for example when a team takes over a database. The declarative form (1.7+) is:

HCL
removed {
  from = aws_db_instance.legacy

  lifecycle {
    destroy = false
  }
}

The imperative form is terraform state rm aws_db_instance.legacy. Both only edit state; the real object stays. Delete the resource block as well, or Terraform will try to create it again.

Python Forget vs destroy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Forcing a replacement

When a resource is broken but Terraform thinks it is fine, rebuild it deliberately:

Terminal
terraform apply -replace="aws_instance.web"

This is the modern replacement for terraform taint, which marked state before the plan; -replace shows the effect in the plan first and needs no extra state edit. Use -target sparingly: it skips dependency analysis and leaves state partly updated. It is an emergency tool, not a workflow.

flowchart TD
  Q{"What do you want?"}
  Q -->|"Rename or move code"| M["moved block"]
  Q -->|"Adopt a real resource"| I["import block"]
  Q -->|"Stop managing, keep object"| R["removed block, destroy = false"]
  Q -->|"Rebuild a broken resource"| P["apply -replace=ADDR"]

Choose the declarative block first; use state commands for one-off repairs.

Safety checklist

  1. Back up state: terraform state pull > state-backup.json.
  2. Make the change (block or command).
  3. Run terraform plan and read it: moves and imports should show no destroy.
  4. Commit the code; apply through your normal pipeline.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You rename aws_s3_bucket.assets to aws_s3_bucket.media in code. What does Terraform plan by default?

    Addresses identify resources. Add a moved block to preserve the object.
  2. 2. Which block adopts an existing cloud resource into state?

    An import block (or terraform import) records an existing object under a resource address.
  3. 3. What does a removed block with destroy = false do?

    It is the declarative equivalent of terraform state rm.
  4. 4. What is the current way to force one resource to be rebuilt?

    -replace shows the replacement in the plan and needs no manual state change.

Summary

  • Resources are tracked by address; renaming code without telling Terraform means destroy and create.
  • Use moved blocks for renames and refactors; state mv is the manual alternative.
  • Use import blocks (and -generate-config-out) to adopt existing resources, then iterate on the plan.
  • Use removed with destroy = false to stop managing something without deleting it.
  • Use apply -replace instead of taint, and treat -target as an emergency tool.

Next: Drift Detection and Refresh