Skip to main content

Infrastructure as code · Intermediate · 20 min

Rename and move Terraform resources without recreating them using moved blocks

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/local 2.9 · hashicorp/random 3.9

You will rename a resource and turn a count resource into for_each with moved blocks so the plan destroys nothing, try terraform state mv for comparison, and hand a resource off with a removed block, backing up the state before each change.

On this page

Terraform tracks every object it manages by an address such as random_pet.server or local_file.page[2]. The address is part of your code, so tidying the code changes it. Rename a resource, wrap it in a module, or swap count for for_each, and Terraform sees one address vanish and another appear. Its default reading of that is "delete the old object, create a new one". For a file that costs nothing. For a database, a DNS zone or a server with a public IP, it means downtime or lost data.

A moved block tells Terraform that the old address and the new one are the same object. The plan then shows a move instead of a replacement, and the move lives in your code where a reviewer can see it.

In this tutorial you build a small configuration with the local and random providers, so nothing touches a cloud account and nothing bills. You will:

  • rename a resource and watch the plan want to destroy it, then fix that with a moved block
  • convert a count resource to for_each with one moved block per instance
  • do a rename with terraform state mv instead, and see what you give up
  • stop managing a resource with a removed block without deleting it
  • save a copy of the state before each change, so any mistake can be undone

The demo lives in ~/moved-demo. Each change follows the same rhythm: back up the state, edit the code, save a plan with terraform plan -out=tfplan, read it, then apply exactly that plan with terraform apply tfplan.

Step 1 · Install Terraform 1.17

Install curl and unzip, then download the Terraform 1.17.2 release for your machine's architecture, check it against HashiCorp's published checksums and put the binary on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

dpkg --print-architecture prints amd64 or arm64, which matches HashiCorp's file names. A binary installed this way gets no updates from apt. To upgrade later, run the same commands with a newer TF_VERSION.

If you pay for data by the megabyte, set a plugin cache before you run terraform init anywhere. Providers are then downloaded once and reused by every project on the machine:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints terraform_1.17.2_linux_amd64.zip: OK (or arm64), and terraform version prints Terraform v1.17.2 on its first line.

Step 2 · Build the starting configuration

The configuration publishes a tiny "site" as local files: a random server name, a welcome message that uses it, and one HTML page per entry in a list, made with count. Create the project and its four files:

Bash
mkdir -p ~/moved-demo/backups
cd ~/moved-demo

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.9"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.9"
    }
  }
}
HCL

cat > variables.tf <<'HCL'
variable "pages" {
  description = "Pages to publish, in menu order."
  type        = list(string)
  default     = ["home", "about", "contact"]
}
HCL

cat > pet.tf <<'HCL'
resource "random_pet" "server" {
  length = 2
}

resource "local_file" "motd" {
  filename = "${path.module}/site/motd.txt"
  content  = "Welcome to ${random_pet.server.id}\n"
}

output "site_name" {
  value = random_pet.server.id
}
HCL

cat > pages.tf <<'HCL'
resource "local_file" "page" {
  count    = length(var.pages)
  filename = "${path.module}/site/${var.pages[count.index]}.html"
  content  = "<h1>${var.pages[count.index]}</h1>\n"
}
HCL

The random name stands in for anything you cannot afford to lose: if random_pet.server is ever recreated, it gets a new name, and the welcome message changes with it. Initialise the project, then save a plan and apply it:

Bash
terraform init
terraform plan -out=tfplan
terraform apply tfplan
terraform state list
terraform output site_name

Applying a saved plan does not ask for confirmation, because you have already read what it will do. Terraform applies exactly that plan, or refuses if the state changed since you made it.

Check it worked

The apply ends with Apply complete! Resources: 5 added, 0 changed, 0 destroyed. terraform state list prints five addresses: local_file.motd, local_file.page[0], local_file.page[1], local_file.page[2] and random_pet.server. terraform output site_name prints a two-word name joined by a hyphen, something like "brave-heron". Write it down: it must survive every change that follows. ls site shows about.html, contact.html, home.html and motd.txt.

Step 3 · Back up the state and rename a resource

Before any change that moves addresses around, save a copy of the state. terraform state pull prints the current state whatever backend holds it, so the same command works for local state and for a remote backend such as S3:

Bash
cd ~/moved-demo
terraform state pull > backups/01-before-rename.tfstate

Terraform also writes a terraform.tfstate.backup next to local state, but it overwrites that file on every write. Your numbered copies are the ones you can go back to. State files can hold secrets in plain text, so keep backups/ out of Git and off shared drives.

Now rename random_pet.server to random_pet.site, a clearer name now that it names the whole site. Rewrite pet.tf with every reference updated:

Bash
cat > pet.tf <<'HCL'
resource "random_pet" "site" {
  length = 2
}

resource "local_file" "motd" {
  filename = "${path.module}/site/motd.txt"
  content  = "Welcome to ${random_pet.site.id}\n"
}

output "site_name" {
  value = random_pet.site.id
}
HCL
terraform plan -out=tfplan

Read the plan, and do not apply it. Terraform no longer finds random_pet.server in the code, so it plans to destroy it. It finds a new random_pet.site with no object behind it, so it plans to create one. The welcome message depends on the name, and its new content is unknown until the new pet exists, so local_file.motd must be replaced too.

Check it worked

The plan marks random_pet.server with will be destroyed, random_pet.site with will be created, and local_file.motd with must be replaced. The summary reads Plan: 2 to add, 0 to change, 2 to destroy. ls backups shows 01-before-rename.tfstate.

Step 4 · Turn the rename into a move with a moved block

Keep the new name in pet.tf and tell Terraform where the object came from. Put refactoring records in their own file, moves.tf, so they are easy to find in review:

Bash
cat > moves.tf <<'HCL'
# random_pet.server was renamed to random_pet.site.
moved {
  from = random_pet.server
  to   = random_pet.site
}
HCL
terraform plan -out=tfplan

Terraform reads moved blocks before it plans. It finds the object at random_pet.server in the state, renames it to random_pet.site, and plans as if the resource had always had that name. The name has not changed, so the welcome message has not either.

The plan shows a line like # random_pet.server has moved to random_pet.site and nothing to add, change or destroy. Apply it, so the state records the new address:

Bash
terraform apply tfplan
terraform state list
terraform output site_name

Check it worked

terraform state list shows random_pet.site and no random_pet.server. terraform output site_name prints the same name you wrote down in step 2, and cat site/motd.txt still welcomes you to it.

Step 5 · Convert a count resource to for_each

The pages use count, so their addresses are positions: local_file.page[0] is home only because home is first in the list. Remove "about" from the middle and contact slides from [2] to [1], which Terraform treats as a change to a different object. for_each keys each instance by a value instead, so local_file.page["contact"] stays contact wherever it sits in the list.

Back up the state, then rewrite pages.tf to use for_each:

Bash
cd ~/moved-demo
terraform state pull > backups/02-before-for-each.tfstate

cat > pages.tf <<'HCL'
resource "local_file" "page" {
  for_each = toset(var.pages)
  filename = "${path.module}/site/${each.key}.html"
  content  = "<h1>${each.key}</h1>\n"
}
HCL
terraform plan -out=tfplan

Look at the plan before you add anything. Terraform does not guess that [0] and ["home"] are the same file, so it plans to destroy the three numbered instances and create three keyed ones: Plan: 3 to add, 0 to change, 3 to destroy. For local files the result would look the same afterwards. For three servers it would be an outage.

Add one moved block per instance, mapping each index to its key. The index must match the position the page had in the old list. Rewrite moves.tf with the earlier block kept:

Bash
cat > moves.tf <<'HCL'
# random_pet.server was renamed to random_pet.site.
moved {
  from = random_pet.server
  to   = random_pet.site
}

# local_file.page moved from count to for_each, keyed by page name.
moved {
  from = local_file.page[0]
  to   = local_file.page["home"]
}

moved {
  from = local_file.page[1]
  to   = local_file.page["about"]
}

moved {
  from = local_file.page[2]
  to   = local_file.page["contact"]
}
HCL
terraform plan -out=tfplan
terraform apply tfplan
terraform state list

If you map an index to the wrong key, for example [1] to "contact", the plan still shows the moves but also wants to replace the two files whose filenames no longer match. A replacement you did not expect is your signal to stop and check the mapping.

Check it worked

The plan before the apply listed three has moved to lines and no other changes. terraform state list now shows local_file.page["about"], local_file.page["contact"] and local_file.page["home"], with no numbered page addresses left. ls site still lists the same four files.

Step 6 · Compare with terraform state mv

Before Terraform 1.1 the only way to rename was to edit the state directly with terraform state mv. It still works, and it is worth knowing for one-off repairs. Rename the welcome message from local_file.motd to local_file.banner this way. Back up first, because this command changes the state immediately, with no plan to review:

Bash
cd ~/moved-demo
terraform state pull > backups/03-before-state-mv.tfstate

cat > pet.tf <<'HCL'
resource "random_pet" "site" {
  length = 2
}

resource "local_file" "banner" {
  filename = "${path.module}/site/motd.txt"
  content  = "Welcome to ${random_pet.site.id}\n"
}

output "site_name" {
  value = random_pet.site.id
}
HCL

terraform state mv -dry-run local_file.motd local_file.banner
terraform state mv local_file.motd local_file.banner
terraform plan

-dry-run lists what would move without touching anything, so run it first every time. The second command rewrites the state, and the plan after it has nothing to do.

The end state is the same as with a moved block, but what you have lost matters on a team:

  • Nobody reviews it. The change happened in your terminal. A pull request shows the renamed resource in pet.tf but nothing that explains why the plan is clean.
  • It only fixes one state. If the same code runs for staging and production, or a colleague has a workspace of their own, each of those states still holds local_file.motd. Their next plan destroys and recreates it, and they get no warning.
  • It does not travel with a module. Anyone using your module would have to run the command themselves after upgrading. A moved block inside the module upgrades them automatically.

Use moved blocks for refactoring and keep terraform state mv for repairs to a single state, done with a backup and -dry-run first.

Check it worked

The dry run prints one line naming both addresses and changes nothing. After the real move, terraform state list shows local_file.banner and no local_file.motd, and terraform plan ends with No changes. Your infrastructure matches the configuration.

Step 7 · Hand a resource over with a removed block

Sometimes a resource has to leave this configuration but keep existing: another team takes it over, or it moves to a different Terraform project. Deleting its block would plan a destroy. A removed block with destroy = false tells Terraform to forget the object and leave it alone.

Say the welcome message now belongs to another team's configuration. Back up the state, take local_file.banner out of pet.tf, and record the handover in a new file:

Bash
cd ~/moved-demo
terraform state pull > backups/04-before-removed.tfstate

cat > pet.tf <<'HCL'
resource "random_pet" "site" {
  length = 2
}

output "site_name" {
  value = random_pet.site.id
}
HCL

cat > handover.tf <<'HCL'
# site/motd.txt is now managed by the content team's configuration.
removed {
  from = local_file.banner

  lifecycle {
    destroy = false
  }
}
HCL
terraform plan -out=tfplan

The plan says local_file.banner will no longer be managed by Terraform, and that nothing will be destroyed. Apply it:

Bash
terraform apply tfplan
terraform state list
cat site/motd.txt

The file is now outside this state. The other configuration adopts it with an import block, which you can learn in /tutorials/import-existing-cloud-resources-into-terraform. Do the removal first and the import second, so two states never manage the same object at the same time.

Check it worked

terraform state list no longer shows local_file.banner, and cat site/motd.txt still prints the welcome message with your site name. terraform plan now shows No changes.

Step 8 · Decide what to keep, then clean up

Leave the moved and removed blocks in place after you apply them. Removing one is a breaking change for any state that has not applied it yet: that state still holds the old address, and once the block is gone its next plan destroys the object. Delete these blocks only when you are sure every copy of the state (every workspace, environment and module user) has applied them. If you rename the same resource again, add a second block from the new name to the newer one and keep the first, so old states can still follow the chain.

Your state backups have done their job. If a step had gone wrong, terraform state push backups/<file>.tfstate would restore one, but take a fresh backup before you push anything, because the push replaces the current state.

To finish, destroy what this configuration still manages. Plan the destroy and read it before applying:

Bash
cd ~/moved-demo
terraform plan -destroy -out=tfplan
terraform apply tfplan

The plan destroys random_pet.site and the three pages. site/motd.txt stays, because nothing manages it any more.

The next command deletes the whole demo folder, including the state, its backups and the unmanaged file. Check you are deleting ~/moved-demo and nothing else:

Bash
cd ~
rm -rf ~/moved-demo

If you installed Terraform only for this tutorial, remove the binary and the plugin cache, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache

Check it worked

Applying the destroy plan ends with Apply complete! Resources: 0 added, 0 changed, 4 destroyed. ls ~/moved-demo then reports No such file or directory.

Next steps

  • Learn when to reach for count and when for for_each in /tutorials/repeat-resources-with-count-for-each-and-dynamic-blocks.
  • See moved blocks carry a real network into a module without downtime in /tutorials/turn-the-relay-network-into-a-reusable-module.
  • Adopt resources someone made by hand with import blocks in /tutorials/import-existing-cloud-resources-into-terraform.
  • Stop a refactor from deleting something important with prevent_destroy in /tutorials/protect-resources-with-lifecycle-rules-in-terraform.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.