Nov 23, 20268 min read

Terraform moved Blocks: Refactor Without Destroying Resources

How Terraform moved blocks rename resources, move them into modules and convert count to for_each without a destroy and create, when to use removed and import blocks instead, how long to keep moved blocks around, and what refactoring looks like when resources are declared in application code.

Illustration for Terraform moved Blocks: Refactor Without Destroying Resources

Every Terraform codebase gets refactored eventually, when a flat main.tf turns into modules or a resource name stops matching what it does. Until Terraform 1.1 that meant a careful terraform state mv for each address in each workspace, and anyone who forgot ran a plan that wanted to destroy a production database.

The moved block puts that mapping in code. This guide covers renames, modules, count to for_each, and when to use removed or import.

What does a moved block do?

Terraform tracks each object in state by its address, such as aws_db_instance.main. Rename the block to aws_db_instance.orders and, without help, the plan destroys the object at the old address and creates a new one at the new address. A moved block records that they are the same object:

resource "aws_db_instance" "orders" { identifier = "acme-orders" engine = "postgres" instance_class = "db.t4g.medium" # ... } moved { from = aws_db_instance.main to = aws_db_instance.orders }

On the next plan, Terraform reports that aws_db_instance.main has moved to aws_db_instance.orders and, if nothing else changed, plans no changes. The refactoring docs describe the rules: the to address must exist in the configuration, the from address must not, and Terraform applies chains of moves in order, so a to b and later b to c both work.

How do you move resources into a module?

Moving a resource into a child module changes its address from aws_s3_bucket.uploads to module.storage.aws_s3_bucket.uploads. One moved block per resource keeps everything in place:

module "storage" { source = "./modules/storage" name = "acme-uploads" } moved { from = aws_s3_bucket.uploads to = module.storage.aws_s3_bucket.this } moved { from = aws_s3_bucket_versioning.uploads to = module.storage.aws_s3_bucket_versioning.this }

Moving a whole module works the same way, with from = module.old and to = module.new, which carries every resource inside it. The bucket-level resources split out in AWS provider 4, such as versioning, encryption and public access blocks, each need their own block, so a plan that still shows a replace usually means one of them was missed.

How do you switch count to for_each?

Changing count to for_each turns aws_sqs_queue.jobs[0] into aws_sqs_queue.jobs["emails"], and each index needs a move to its key:

moved { from = aws_sqs_queue.jobs[0] to = aws_sqs_queue.jobs["emails"] } moved { from = aws_sqs_queue.jobs[1] to = aws_sqs_queue.jobs["exports"] }

The for_each vs count guide covers why the conversion is worth it. Check the plan says "has moved to" for every instance and shows zero to add and zero to destroy before you apply.

When should you use removed instead?

Sometimes the goal is the opposite of a move: Terraform should stop managing a resource without deleting it, for example a log bucket another team is taking over. Deleting the block alone plans a destroy. On Terraform 1.7 and later, a removed block with destroy = false makes Terraform forget the object instead:

removed { from = aws_s3_bucket.audit_logs lifecycle { destroy = false } }

After the apply, the bucket keeps running in AWS and is no longer in this state. This replaces terraform state rm, with the same advantage moved blocks have over state mv: it is reviewed in a pull request and applied by every workspace that uses the config.

How do you move a resource between state files?

moved only works inside one state, so splitting a monolithic configuration into a network config and an app config takes two steps. The old config gets a removed block with destroy = false, and the new one gets an import block, available since Terraform 1.5, with the resource's cloud ID:

# in the new configuration import { to = aws_db_instance.orders id = "acme-orders" } resource "aws_db_instance" "orders" { identifier = "acme-orders" engine = "postgres" instance_class = "db.t4g.medium" # ... }

Apply the removal first and the import second, and between the two the database is in neither state, which is fine as long as nobody applies the old config with the block restored. terraform plan -generate-config-out=generated.tf can write a starting resource block from the imported object, as the generated configuration docs describe.

Can you move between resource types?

Terraform 1.8 and later let a moved block change the resource type when the provider supports it. The common case is retiring null_resource from the null provider in favour of the built-in terraform_data resource:

moved { from = null_resource.run_migrations to = terraform_data.run_migrations }

Most AWS resource types do not accept moves from other types, and a plan that errors with "Unsupported target resource type" means the provider has no conversion, so the fallback is removed plus import.

How long should you keep moved blocks?

A moved block is applied once per state, and it has to stay in the code until every state that uses the configuration has been applied with it. For a root configuration with one production and one staging workspace, that can be a day. For a shared module used by twenty teams, deleting a moved block from a new module version means every consumer that skipped the earlier version plans a destroy when they upgrade. The refactoring docs strongly recommend keeping every historical moved block in published modules, and a moved.tf file with a comment naming the release that added each block keeps them out of the way.

What does refactoring look like with Encore?

Encore

Encore brings infrastructure from code, and each database, topic or bucket is identified by the name string in its declaration, not by an address in a state file. Renaming the variable that holds it, moving the declaration to another file in the service or reorganizing the code around it leaves the resource alone, so most of the refactors above need no extra step at all.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create uploads-api --example=ts/hello-world$ cd uploads-api && mkdir -p uploads/migrations

The database and bucket live in their own file, and the endpoint file imports them, which is the kind of split that would move addresses in a Terraform module:

// uploads/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("uploads");

The bucket and database are declared by name:

// uploads/resources.ts import { SQLDatabase } from "encore.dev/storage/sqldb"; import { Bucket } from "encore.dev/storage/objects"; // The names "uploads" and "user-uploads" identify the resources. // Renaming these variables or moving this file within the service does not change them. export const uploadsDB = new SQLDatabase("uploads", { migrations: "./migrations" }); export const files = new Bucket("user-uploads");

The migration for the uploads table:

-- uploads/migrations/1_uploads.up.sql CREATE TABLE uploads ( id BIGSERIAL PRIMARY KEY, object_key TEXT NOT NULL UNIQUE, owner_id TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() );

Then the endpoints that use them:

// uploads/uploads.ts import { api, APIError } from "encore.dev/api"; import { randomUUID } from "node:crypto"; import { uploadsDB, files } from "./resources"; export const createUploadURL = api( { expose: true, method: "POST", path: "/uploads" }, async (p: { ownerID: string }): Promise<{ key: string; url: string }> => { if (!p.ownerID) throw APIError.invalidArgument("ownerID is required"); const key = `${p.ownerID}/${randomUUID()}`; await uploadsDB.exec`INSERT INTO uploads (object_key, owner_id) VALUES (${key}, ${p.ownerID})`; const { url } = await files.signedUploadUrl(key, { ttl: 900 }); return { key, url }; }, );

encore run starts Postgres locally and stores bucket objects on the local filesystem, so the endpoint works before any deploy. On deploy, Encore provisions the database and the bucket in your cloud and an IAM role for the service, or a service account on GCP.

Changing the name string itself is the one refactor that does create a new resource, and there is no moved equivalent for it, since the name is the identity. The old database is not lost when that happens: per the managing infrastructure docs, stateful resources are only deleted when they are unused and a user has confirmed the deletion, and on your own cloud SQL databases also have deletion protection on at the provider level. Keep names stable and treat a rename as a data migration.

A coding agent that reorganizes a service into smaller files moves the declarations with the code and runs the service locally, and no moved block or state file is part of the change.

Best fit: Teams that refactor service code often and want databases and buckets to stay put while files, variables and modules move around them.

Terraform moved block checklist

  • Add a moved block for every renamed resource or module and every count index you convert.
  • Confirm the plan says "has moved to" with zero to add and zero to destroy.
  • Use removed with destroy = false to stop managing a resource without deleting it.
  • Move between configurations with removed in the old one and import in the new one.
  • Keep moved blocks in shared modules until every consumer has upgraded.

Frequently asked questions

What does a moved block do in Terraform?

A moved block tells Terraform that an object recorded at one address in state is now at another, for example after renaming a resource or moving it into a module. During plan, Terraform updates the state address instead of destroying the old object and creating a new one.

Is a moved block better than terraform state mv?

Yes. A moved block is code, so it is reviewed in a pull request and applied by every workspace and module consumer on their next plan, while terraform state mv changes one state by hand and leaves other copies of the module to plan a destroy.

How do I stop managing a resource in Terraform without deleting it?

On Terraform 1.7 or later, delete the resource block and add a removed block with from set to its address and lifecycle { destroy = false }. Terraform forgets the object on the next apply and leaves it running in the cloud.

Can a moved block move a resource to a different state file?

No. moved works within one state. To move a resource to another configuration, add a removed block with destroy = false in the old one and an import block with the resource ID in the new one.

Do Encore databases and buckets need a moved block when service code is refactored?

No. Encore provisions databases and buckets from declarations in the service, and a refactor that moves files or modules in the application does not destroy those resources. A moved block is still the right tool for resources you manage in Terraform.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders