You have been carrying a promise for two modules. In Resource and Data Blocks you migrated from count to for_each and the plan answered with a devastating 4 to add, 0 to change, 4 to destroy, without a single resource having actually changed. In State Files you learnt to fix it with terraform state mv, and discovered the problem with the cure: it is a command you run, in your terminal, that does not appear in the PR and that your colleague — or the pipeline — will never run. This lesson closes the circle with the modern solution: the moved and removed blocks, which turn state surgery into versioned, reviewable code. And it closes the whole of module 3 too.

  1. The problem: the address is the identity

Recall the central idea from Understanding State: the state is a map of identities between the address you write and the provider's real object. That address is made of four pieces:

module.network.aws_subnet.private["eu-west-1a"]
└─────┬──────┘└───┬─────┘└──┬───┘└─────┬──────┘
   module       type      name   instance key

Any change to any of those pieces produces a new address, and a new address is, as far as Terraform is concerned, a different resource. These four refactorings, all of them purely cosmetic from the infrastructure's point of view, trigger a destroy + create:

Refactoring Address before Address after
Renaming the resource local_file.inventory local_file.general_inventory
Moving it into a module aws_vpc.main module.network.aws_vpc.main
Taking it out of a module module.network.aws_vpc.main aws_vpc.main
From count to for_each local_file.service[0] local_file.service["web"]

With a local_file that means deleting and rewriting a file: annoying, harmless. With EcoMarket's production PostgreSQL database it means destroying the database and creating an empty one. That is why improving the structure of your code is frightening in Terraform in a way it is in no other language: here, renaming a variable can delete data.

The moved and removed blocks take that fear away. And that matters more than it seems: a team that cannot refactor safely ends up with code nobody dares to touch.

flowchart TB
    A["You change a resource's<br/>ADDRESS in the .tf"] --> B{"Does Terraform know<br/>it is the same object?"}
    B -- "No: nothing tells it" --> C["Plan: destroy + create<br/>the data is lost"]
    B -- "Yes: moved block" --> D["Plan: has moved to...<br/>0 to add, 0 to change, 0 to destroy"]
    B -- "Yes: terraform state mv" --> E["Works ONLY in the state<br/>where you ran it"]

    style C fill:#ffe5e5,stroke:#c53030
    style D fill:#e9f7ef,stroke:#2f855a
    style E fill:#fff6e5,stroke:#b7791f

  1. The demonstration: refactor and watch the plan burn

We start from EcoMarket's real module 2 state. Three files created with count:

# main.tf — current version, applied and in the state
locals {
  services = ["web", "api", "batch"]
  prefix   = "${var.project}-${var.environment}"
}

resource "local_file" "service" {
  count = length(local.services)

  filename = "${path.module}/${local.prefix}-${local.services[count.index]}.json"
  content  = jsonencode({
    service     = local.services[count.index]
    environment = var.environment
  })
}
$ terraform state list
local_file.service[0]
local_file.service[1]
local_file.service[2]

Now you apply module 2's recommendation — for_each by default, count only for switches — and rewrite:

resource "local_file" "service" {
  for_each = toset(local.services)

  filename = "${path.module}/${local.prefix}-${each.key}.json"
  content  = jsonencode({
    service     = each.key
    environment = var.environment
  })
}
$ terraform plan
Terraform will perform the following actions:

  # local_file.service[0] will be destroyed
  # (because resource uses count, not for_each)
  - resource "local_file" "service" {
      - filename = "./ecomarket-dev-web.json" -> null
      - id       = "1a2b3c4d..." -> null
    }

  # local_file.service[1] will be destroyed  (same reason)
  # local_file.service[2] will be destroyed  (same reason)

  # local_file.service["api"] will be created
  + resource "local_file" "service" {
      + filename = "./ecomarket-dev-api.json"
      + id       = (known after apply)
    }

  # local_file.service["batch"] will be created
  # local_file.service["web"] will be created

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

Three destructions and three creations for a change that does not alter a single byte of the final result. Look at the reason Terraform gives: because resource uses count, not for_each. It is not a bug or a limitation: it is the direct consequence of the address being the identity.

  1. terraform state mv versus the moved block

You already know the imperative solution:

$ terraform state mv 'local_file.service[0]' 'local_file.service["web"]'
$ terraform state mv 'local_file.service[1]' 'local_file.service["api"]'
$ terraform state mv 'local_file.service[2]' 'local_file.service["batch"]'

It works. But look at its properties next to the declarative one:

Aspect terraform state mv moved block
Nature Imperative: a command that is run Declarative: an intention that is written
Where it lives In your Bash history In the repository, next to the change
Reviewed in the PR? No Yes: it reads like any other code
Does the plan show it? No: you have to trust it was done Yes: has moved to appears in the plan
Who runs it? Each person, in each state, by hand Terraform, automatically, on every apply
Risk of forgetting High: whoever does not run it will destroy None
Does it work in CI? Only with an added manual step Yes, with nothing special
Reversible With the inverse mv, by hand By reverting the commit
Multiple states (dev/staging/prod) It has to be run in all three It applies itself in each one
Published modules Impossible: you do not control other people's states It is the only viable option

The last two rows are decisive. If EcoMarket has three environments with three separate states, state mv means running the same commands three times, against three backends, without making a mistake. And if you publish a module used by other teams, you have no access to their states: the only way to refactor it without breaking their infrastructure is for the module itself to carry the moved blocks inside.

Rule for EcoMarket: moved by default; state mv only for one-off rescues that do not fit in the configuration, such as moving a resource between two different states.

  1. The moved block: syntax and accepted addresses

Available since Terraform 1.1. Its form is minimal:

moved {
  from = local_file.service[0]
  to   = local_file.service["web"]
}

Important characteristics:

  • It is a top-level block, like resource or variable. It does not go inside anything.
  • It has no label: you do not write moved "something".
  • from and to are addresses, not strings: they go without quotes around the full address (the quotes of a for_each key do go in, because they are part of the address).
  • It can be in any .tf file of the module where the resource lives. By convention, EcoMarket groups them in moved.tf.
  • It has no effect on the infrastructure: it only rewrites the address inside the state during the apply.

Which addresses it accepts:

Type Example Valid?
A whole resource local_file.inventory Yes
An instance by index local_file.service[0] Yes
An instance by key local_file.service["web"] Yes
A resource inside a module module.network.aws_vpc.main Yes
A whole module module.network Yes
A module instance module.environment["dev"] Yes
A data source data.local_file.tags No: data sources are not held in the state as managed objects
Between different types local_file.x → local_sensitive_file.x No
Between unrelated modules See section 12 With caveats

  1. What a moved looks like in the plan

This is the property that gives the most peace of mind: the move is visible before it is carried out.

# moved.tf
moved {
  from = local_file.service[0]
  to   = local_file.service["web"]
}

moved {
  from = local_file.service[1]
  to   = local_file.service["api"]
}

moved {
  from = local_file.service[2]
  to   = local_file.service["batch"]
}
$ terraform plan
Terraform will perform the following actions:

  # local_file.service[0] has moved to local_file.service["web"]
    resource "local_file" "service" {
        id       = "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
        filename = "./ecomarket-dev-web.json"
        # (3 unchanged attributes hidden)
    }

  # local_file.service[1] has moved to local_file.service["api"]
    resource "local_file" "service" { ... }

  # local_file.service[2] has moved to local_file.service["batch"]
    resource "local_file" "service" { ... }

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

Three details worth reading carefully:

  1. Plan: 0 to add, 0 to change, 0 to destroy. That is the result we have been after since module 2. The promise, delivered.
  2. The symbol for the moved resource is not +, - or ~: there is no symbol. Nothing is being done to the infrastructure, only a state entry is being relabelled.
  3. If there is a move and a change, Terraform shows both: has moved to ... followed by a ~ with the attributes that change. They are independent operations that stack up.

A very practical nuance: even though the plan says 0 to destroy, you still have to apply. The moved takes effect during the apply; the plan only anticipates it. Applying a plan that only moves things is quick and safe, but it is mandatory for the state to be rewritten.

  1. Chaining moves

moved blocks are resolved transitively. If a resource has changed name twice over several months, you can leave both blocks in place:

# January: renamed from "file" to "inventory".
moved {
  from = local_file.file
  to   = local_file.inventory
}

# March: renamed from "inventory" to "general_inventory".
moved {
  from = local_file.inventory
  to   = local_file.general_inventory
}

A state that still holds local_file.file will travel the whole chain to local_file.general_inventory in a single apply:

  # local_file.file has moved to local_file.general_inventory

This is what lets different environments be out of step: dev is already on inventory, prod is still on file, and the same blocks work for both. With state mv you would have to know exactly where each state stood before running anything.

What you cannot do is close a cycle:

moved {
  from = local_file.a
  to   = local_file.b
}
moved {
  from = local_file.b
  to   = local_file.a
}     # ERROR
╷
│ Error: Cyclic dependency in move statements
│
│ The following chained move statements form a cycle, and so there is no
│ final location to move objects to:
│   - local_file.a → local_file.b
│   - local_file.b → local_file.a
╵

  1. Moves into and out of modules

This is the case you will use most, and not by chance: module 4 of this course consists precisely of extracting EcoMarket's code into reusable modules. Without moved, that refactoring would destroy the entire infrastructure.

7.1. Moving resources into a module

Before, everything in the root:

# main.tf (before)
resource "local_file" "inventory" { ... }
resource "random_pet" "suffix"    { ... }

Afterwards, extracted into modules/inventory/:

# main.tf (after)
module "inventory" {
  source      = "./modules/inventory"
  project     = var.project
  environment = var.environment
}
# moved.tf
moved {
  from = local_file.inventory
  to   = module.inventory.local_file.inventory
}

moved {
  from = random_pet.suffix
  to   = module.inventory.random_pet.suffix
}
  # local_file.inventory has moved to module.inventory.local_file.inventory
  # random_pet.suffix has moved to module.inventory.random_pet.suffix

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

7.2. Taking resources out of a module, and moving whole modules

# Take a resource out of a module and into the root.
moved {
  from = module.inventory.local_file.inventory
  to   = local_file.inventory
}

# Rename a whole module: it drags ALL its internal resources along.
moved {
  from = module.inventory
  to   = module.ecomarket_inventory
}

# Turn a single module into a module with for_each per environment.
moved {
  from = module.inventory
  to   = module.inventory["dev"]
}

The third case is particularly elegant: a single block relocates every resource in the module, however many there are. Terraform applies the move recursively.

7.3. A module that refactors itself internally

Here is the reason moved is indispensable in shared modules. If you publish ecomarket/inventory and in version 2.0 you rename an internal resource, the moved blocks go inside the module:

# modules/inventory/moved.tf — inside the module itself
moved {
  from = local_file.output
  to   = local_file.inventory
}

When a consumer upgrades from 1.4.0 to 2.0.0, their plan will show the move and destroy nothing, without them having to do anything at all. That is the contract of a well-maintained module, and it is developed in Module Composition and Versioning.

  1. From count to for_each with moved

The case that opened this lesson, generalised. You have to write one block per instance, because each index goes to a different key:

moved {
  from = local_file.service[0]
  to   = local_file.service["web"]
}
moved {
  from = local_file.service[1]
  to   = local_file.service["api"]
}
moved {
  from = local_file.service[2]
  to   = local_file.service["batch"]
}

moved blocks accept neither for_each nor expressions. from and to are literal addresses. If you have forty instances, that is forty blocks; generate them with a script if you must, but write them out.

The index → key mapping is not arbitrary: it has to respect the real order that existed in the original list.

# Before writing a single moved block, find out what is at each index.
$ for i in 0 1 2; do
    echo -n "[$i] -> "
    terraform state show "local_file.service[$i]" | grep 'filename' | head -1
  done
[0] -> filename = "./ecomarket-dev-web.json"
[1] -> filename = "./ecomarket-dev-api.json"
[2] -> filename = "./ecomarket-dev-batch.json"

If you get it wrong and map [0] to "api", the plan will not fail: Terraform will move the entry and then detect that the attributes do not match, proposing to modify or replace the resources. With a local_file the file gets rewritten; with a database, it gets replaced. Always verify the mapping with state show before applying, and check that the plan says 0 to change.

And an extra warning: with toset() over a list, the keys are the list's own values, so the order of the original list and that of the keys need not coincide (sets are ordered alphabetically). That is why the mapping is taken from the state, not from reading the code.

  1. The life cycle of the moved block itself

A reasonable question: if the move has already been applied in every environment, do you have to leave the block there forever?

A moved whose from does not exist in the state is harmless: Terraform ignores it silently. It does not fail, it does not warn. So there is no urgency about deleting them.

Situation When to delete it?
Root configuration, few environments, all applied After applying in the last environment; a clean-up once a quarter
Root configuration, many environments or slow deployments When you are sure that every state has been through the apply
A module internal to the team Leave it for at least a couple of versions
A public module, or one shared across teams Leave it for a long time, ideally until the next major version change

The reason for the last case: you do not know who is using which version. Somebody may jump from 1.2.0 to 2.3.0 six months from now; if you have deleted the moved from 2.0.0, their apply will destroy their infrastructure. A public module's moved blocks are part of its compatibility contract, and they are removed only in a documented major version change.

A practical convention for EcoMarket: a moved.tf file with the blocks grouped by date and commented with the originating PR.

# moved.tf

# 2026-09-22 — PR #412: migration from count to for_each in local_file.service.
# Can be removed once dev, staging and prod have applied. Applied in:
#   dev (22/09), staging (23/09), prod (pending)
moved {
  from = local_file.service[0]
  to   = local_file.service["web"]
}
moved {
  from = local_file.service[1]
  to   = local_file.service["api"]
}
moved {
  from = local_file.service[2]
  to   = local_file.service["batch"]
}

  1. The removed block: stop managing without destroying

Available since Terraform 1.7. It solves the inverse operation: taking a resource out of Terraform's management without destroying it, declaratively.

The problem it solves is the mirror image of moved's. If EcoMarket decides that the images bucket is to be managed by the data team in their own repository, you have three bad options and one good one:

Method What happens to the real object Traceability Problem
Deleting the resource block from the .tf It is destroyed The PR shows it It destroys what you wanted to keep
terraform state rm It survives None Imperative; it has to be run in every state and you have to remember to remove the block
lifecycle { prevent_destroy } and touch nothing It survives — It does not stop managing it; the plan keeps proposing changes
A removed block It survives In the code and in the plan None

The syntax:

# 1. The resource "local_file" "images" block is DELETED from the .tf.
# 2. In its place, you add:

removed {
  from = local_file.images

  lifecycle {
    # false = forget about it, but do NOT destroy it.
    destroy = false
  }
}
$ terraform plan
Terraform will perform the following actions:

  # local_file.images will no longer be managed by Terraform, but will not be
  # destroyed
  # (destroy = false is set in the removed block)
 . resource "local_file" "images" {
        id       = "9f3a2b1c8d7e6f5a4b3c2d1e0f9a8b7c6d5e4f3a"
        filename = "./ecomarket-dev-images.json"
    }

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

Key points:

  • The corresponding resource block must have been deleted. removed and resource for the same address are incompatible: Terraform errors out.
  • from accepts the same addresses as in moved, whole modules and specific instances included.
  • After applying, the resource disappears from the state and the real object carries on existing, now with no owner. From that moment on, nobody manages it: make sure another repository imports it, or you will end up with orphaned infrastructure, which is both a cost problem and a security problem.

10.1. removed for a whole module

# The module "legacy" block is deleted and you declare:
removed {
  from = module.legacy

  lifecycle {
    destroy = false
  }
}

A single block releases every resource in the module. It is the clean way to dismantle a part of the repository that is passing to another team.

10.2. destroy = true: the less obvious case

removed {
  from = local_file.temporary

  lifecycle {
    destroy = true
  }
}

With destroy = true you are telling Terraform that it should destroy the object. So how does that differ from simply deleting the resource block, which also destroys it? In two ways:

  1. Explicit intent. Whoever reviews the PR sees a declaration saying "this is being destroyed on purpose", instead of having to infer it from a block that is no longer there. In a large configuration, a deleted resource is easily lost in the diff.
  2. Module destroy-time provisioners. When retiring a module that had a provisioner with when = destroy, the removed block lets you declare that exit logic, which would otherwise disappear along with the code. Provisioners are covered in 05-05.

Day to day, the overwhelmingly common use is destroy = false.

10.3. removed versus state rm

terraform state rm removed block
Nature Imperative Declarative
Visible in the PR No Yes
Visible in the plan No Yes
Applies itself in each environment No: one by one, by hand Yes
Risk of forgetting to remove the resource block High: the next plan recreates the resource as a duplicate None: they are incompatible, Terraform forces it
Can it destroy? No, never Yes, with destroy = true
Minimum version All 1.7

The risk row is the decisive one. The classic state rm accident — removing it from the state and forgetting to delete the block, so the next apply creates a duplicate object — is structurally impossible with removed.

  1. Guided exercise: migrating EcoMarket to for_each without destroying anything

Let us settle module 2's promise, step by step and runnable with the local provider.

Step 1. The starting point. In a fresh directory:

# main.tf
terraform {
  required_version = "~> 1.9"
  required_providers {
    local = { source = "hashicorp/local", version = "~> 2.5" }
  }
}

variable "project" {
  type    = string
  default = "ecomarket"
}

variable "environment" {
  type    = string
  default = "dev"
}

locals {
  services = ["web", "api", "batch"]
  prefix   = "${var.project}-${var.environment}"

  common_tags = {
    Project     = var.project
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

resource "local_file" "service" {
  count = length(local.services)

  filename = "${path.module}/${local.prefix}-${local.services[count.index]}.json"
  content = jsonencode({
    service = local.services[count.index]
    prefix  = local.prefix
    tags    = local.common_tags
  })
}
$ terraform init && terraform apply -auto-approve
$ terraform state list
local_file.service[0]
local_file.service[1]
local_file.service[2]

Step 2. Write down the real mapping, which is the step you must never skip:

$ for i in 0 1 2; do
    printf '[%s] %s\n' "$i" "$(terraform state show "local_file.service[$i]" | awk -F'"' '/filename/{print $2}')"
  done
[0] ./ecomarket-dev-web.json
[1] ./ecomarket-dev-api.json
[2] ./ecomarket-dev-batch.json

Step 3. Rewrite with for_each and watch the disaster (without applying):

resource "local_file" "service" {
  for_each = toset(local.services)

  filename = "${path.module}/${local.prefix}-${each.key}.json"
  content = jsonencode({
    service = each.key
    prefix  = local.prefix
    tags    = local.common_tags
  })
}
$ terraform plan
Plan: 3 to add, 0 to change, 3 to destroy.

Step 4. Add the moved blocks according to the mapping you noted down:

# moved.tf
# 2026-09-22 — PR #412: count -> for_each in local_file.service.
# Mapping verified with `terraform state show` before writing these blocks.
moved {
  from = local_file.service[0]
  to   = local_file.service["web"]
}

moved {
  from = local_file.service[1]
  to   = local_file.service["api"]
}

moved {
  from = local_file.service[2]
  to   = local_file.service["batch"]
}

Step 5. Check the plan. This is the line we have been chasing since module 2:

$ terraform plan
  # local_file.service[0] has moved to local_file.service["web"]
  # local_file.service[1] has moved to local_file.service["api"]
  # local_file.service[2] has moved to local_file.service["batch"]

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

Step 6. Apply and confirm. Remember: even with no changes, you have to apply so that the state gets rewritten.

# Note a file's inode to prove that it is NOT recreated.
$ ls -i ecomarket-dev-web.json
1835293 ecomarket-dev-web.json

$ terraform apply -auto-approve
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

$ terraform state list
local_file.service["api"]
local_file.service["batch"]
local_file.service["web"]

# Same inode: it is THE SAME file, not a new one.
$ ls -i ecomarket-dev-web.json
1835293 ecomarket-dev-web.json

Step 7. The acid test. Now that you are on for_each, remove "api" from the list and note the difference from module 2:

$ terraform plan
  # local_file.service["api"] will be destroyed
  # (because key ["api"] is not in for_each map)

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

A single destruction, the one you asked for. No reindexing, no side effects. The migration was worth it and did not cost a single resource.

  1. Limitations and frequent errors

Error Message or symptom Cause and fix
A moved cycle Cyclic dependency in move statements Two blocks pointing at each other. Leave only the net move
A non-existent from Silence: nothing happens It is not an error. But if you expected a move and the plan still proposes destroying, the from address is misspelt: check it with terraform state list
Different types Resource type mismatch moved does not turn a local_file into a local_sensitive_file. For that: state rm + import
to already taken Moved object collides with existing object The destination already exists in the state. Decide which one to keep
moved + deleted resource Moved object still exists, or a destroy plan The to must correspond to a resource that is in the configuration
State already moved by hand The moved does nothing, the plan is clean That is the correct behaviour: from no longer exists. The block is idempotent
removed with the resource still present Removed resource block still exists You have to delete the resource block before declaring the removed
moved on a data source An invalid address error Data sources are not moved: they are re-read. Just rename it
Expressions in from/to Invalid expression Literal addresses only. No variables, no for_each, no interpolation

Two clarifications about cases that raise doubts:

"I did a state mv by hand and then added the moved." Nothing happens: the from no longer exists in the state and the block is ignored. It is the usual migration route for teams coming from the imperative method — you can add the blocks after the fact so that the remaining environments sort themselves out.

"Can I move a resource to another configuration with moved?" No. moved operates within a single state. To move between different states you still need terraform state mv -state-out=..., or the combination of removed at the source plus import at the destination, which is cleaner and leaves a trace in both repositories.

  1. How this is reviewed in a PR

A PR containing moved or removed blocks is a delicate PR, and it deserves a checklist of its own:

# What to check Why
1 Does the attached plan say 0 to destroy? It is the main verification. If the PR does not attach the plan, ask for it before reviewing anything else
2 Does each moved have its resource in the configuration? A to with no resource destroys instead of moving
3 Has the index → key mapping been verified with state show? A crossed mapping does not fail: it silently replaces resources
4 Is there a comment with the date and the reason? It tells you when they can be retired
5 Do the removed blocks carry destroy = false when the object is to be kept? A careless destroy = true is a real destruction
6 For a removed: who manages the object from now on? It avoids orphaned infrastructure with no owner and no budget
7 Has it already been applied in any environment, and which? Environments run out of step; it is worth recording
8 Is any old moved being deleted in this same PR? Retiring a moved that some state still needs is destructive

And a process recommendation: separate the refactoring from the functional change. A PR that moves resources into a module and also changes the database sizing is impossible to review, because you cannot tell which part of the plan comes from which. First the moved with a clean plan; then, in another PR, the real change.

Security note. A removed with destroy = false on a resource that holds data — a database, a bucket — leaves that object outside all Terraform control: the policies, the encryption and the tags you managed from the code will no longer be applied to it. Before applying it, agree with the security team who takes over its governance and document the handover.

Common Mistakes and Tips

  • Writing the moved without verifying the mapping. state show first, blocks afterwards. A crossed mapping gives no error: it replaces resources.
  • Believing that a plan with has moved to needs no apply. The move takes effect in the apply. Until then, the state is as it was.
  • Trying to use for_each or variables inside a moved. It accepts literal addresses only. If there are many, generate the blocks with a script.
  • Deleting the moved blocks the same day they are applied in dev. staging and prod are still to come, and maybe somebody with an old branch. Wait until every state has been through.
  • Retiring the moved blocks from a public module. They are part of its compatibility contract: they are removed only in a documented major version change.
  • Using removed without agreeing who takes charge of the object. Orphaned infrastructure: nobody patches it, nobody destroys it, and it stays on the bill.
  • Mixing refactoring and a functional change in the same PR. It makes the plan unreadable and cancels out the method's main advantage.
  • Tip: group the blocks in a moved.tf with comments including the date, the PR and which environments it has already been applied in. Six months from now, nobody will remember why they are there.
  • Tip: if you are going to extract resources into modules (the whole of module 4), write the moved blocks at the same time as you move the code, not afterwards. It is much easier to get the addresses right when you have the change in front of you.
  • Tip: in a repository with several environments, always apply in the same order — dev, staging, prod — and record it. Being out of step is normal; confusion about who is where is not.

Exercises

Exercise 1: renaming and nesting into a module

  1. Start from a configuration with local_file.inventory and random_pet.suffix applied.
  2. Rename local_file.inventory to local_file.general_inventory and check the plan without applying.
  3. Add the corresponding moved and verify that the plan becomes 0 to add, 0 to change, 0 to destroy. Apply.
  4. Now extract both resources into a local module ./modules/inventory (with its input variables) and add the necessary moved blocks.
  5. Verify that the plan is still clean, apply, and check with terraform state list that the addresses now carry the module.inventory. prefix.
  6. Chain it: without deleting the previous blocks, rename the module to module.ecomarket_inventory and check that everything still works with a single new block.

Exercise 2: stop managing a resource with removed

  1. Add a local_file.legacy to your configuration and apply it. Note its id and check that the file exists.
  2. Delete the resource block and run terraform plan. What does it propose?
  3. Discard that plan (do not apply it). Replace the block with a removed carrying lifecycle { destroy = false } and plan again. Compare the two outputs.
  4. Apply and verify two things: that terraform state list no longer includes it and that the file still exists on disk.
  5. Run terraform plan once more. Why does it propose nothing, if the file is still there?
  6. Answer: what would have happened with destroy = true? And how does that differ from having deleted the resource block in point 2?

Exercise 3: diagnosing badly written moved blocks

For each fragment, say what happens when planning and how it is fixed:

# A
moved {
  from = local_file.a
  to   = local_file.b
}
moved {
  from = local_file.b
  to   = local_file.a
}
# B  (local_file.old does NOT exist in the state; local_file.new IS in the .tf)
moved {
  from = local_file.old
  to   = local_file.new
}
# C  (the resource "local_file" "target" block was deleted from the .tf)
moved {
  from = local_file.source
  to   = local_file.target
}
# D
moved {
  from = local_file.service[count.index]
  to   = local_file.service[each.key]
}

Solutions

Solution 1:

# Point 2
$ terraform plan
Plan: 1 to add, 0 to change, 1 to destroy.
# Point 3
moved {
  from = local_file.inventory
  to   = local_file.general_inventory
}
$ terraform plan
  # local_file.inventory has moved to local_file.general_inventory
Plan: 0 to add, 0 to change, 0 to destroy.
# Point 4
module "inventory" {
  source      = "./modules/inventory"
  project     = var.project
  environment = var.environment
}

moved {
  from = local_file.general_inventory
  to   = module.inventory.local_file.general_inventory
}

moved {
  from = random_pet.suffix
  to   = module.inventory.random_pet.suffix
}
# Point 5
$ terraform state list
module.inventory.local_file.general_inventory
module.inventory.random_pet.suffix
# Point 6: a single block moves the whole module with all its contents.
moved {
  from = module.inventory
  to   = module.ecomarket_inventory
}

The earlier blocks do no harm: a state coming from the original configuration will travel the whole chain (local_file.inventory → general_inventory → module.inventory.... → module.ecomarket_inventory....) in a single apply.

Solution 2:

# Point 2: deleting the resource block means DESTROYING.
$ terraform plan
  # local_file.legacy will be destroyed
  # (because local_file.legacy is not in configuration)
Plan: 0 to add, 0 to change, 1 to destroy.
# Point 3
removed {
  from = local_file.legacy
  lifecycle {
    destroy = false
  }
}
  # local_file.legacy will no longer be managed by Terraform, but will not be
  # destroyed
Plan: 0 to add, 0 to change, 0 to destroy.

The difference between the two outputs is exactly the one we were after: 1 to destroy versus 0 to destroy.

# Point 4
$ terraform apply -auto-approve
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

$ terraform state list | grep legacy || echo "no longer in the state"
no longer in the state

$ ls ecomarket-dev-legacy.json
ecomarket-dev-legacy.json      # the real object SURVIVES

Point 5: it proposes nothing because Terraform no longer knows about that file. It is neither in the configuration nor in the state, so as far as Terraform is concerned it does not exist. That is precisely the risk: if nobody adopts it in another repository, it is orphaned infrastructure.

Point 6: with destroy = true, the file would have been deleted, just as in point 2. The difference from deleting the resource block is not in the effect but in the declared intent: the PR shows an explicit statement that the destruction is deliberate, instead of forcing the reviewer to deduce it from an absent block. It is also what lets you preserve destroy-time provisioner logic when retiring a module.

Solution 3:

Case What happens Fix
A Error: Cyclic dependency in move statements. There is no final destination Leave only the net move. If a should end up as b, a single block from = local_file.a, to = local_file.b
B Nothing: Terraform ignores the block silently because from does not exist. If local_file.new is not in the state either, the plan will propose creating it That is the correct behaviour and it is idempotent. If you expected a move, the from address is wrong: check it with terraform state list
C The object is moved to local_file.target and, immediately afterwards, Terraform sees that the address is not in the configuration and proposes destroying it. Result: 1 to destroy A moved's to must exist in the .tf. If what you want is to stop managing it, use a removed block with destroy = false
D Error: Invalid expression / an invalid address. count.index and each.key do not exist outside a resource Write one literal block per instance: from = local_file.service[0], to = local_file.service["web"], and so on

Conclusion

You have settled the course's last debt with module 2:

  • In Terraform, the address is the identity. Renaming a resource, moving it into a module, taking it out or changing from count to for_each produces a new address, and Terraform reads that as destroy + create.
  • terraform state mv fixes it, but it is imperative: it does not appear in the PR, the plan does not show it, it has to be run in every state and whoever does not run it will destroy. In a shared module it is simply not viable.
  • The moved block (Terraform 1.1+) declares the address change in the code: from and to as literal addresses, no expressions, visible in the plan as has moved to and with no effect whatsoever on the real infrastructure.
  • moved blocks chain transitively, which lets dev, staging and prod run out of step without anyone having to know where each one stands; and a non-existent from is silently ignored, so they are idempotent.
  • They serve for renaming, for moving into and out of modules — which is exactly what you are about to do next — for moving whole modules and for migrating from count indexes to for_each keys, with one block per instance and the mapping verified beforehand with state show.
  • It is worth not deleting them too soon, and in a public module keeping them until the next major version change: they are part of its compatibility contract.
  • The removed block (Terraform 1.7+) does the inverse: it stops managing a resource or a whole module with lifecycle { destroy = false }, declaratively and without state rm's classic risk of forgetting the resource block and ending up with duplicate objects. With destroy = true it declares a deliberate, explicit destruction.
  • And all of this is reviewed in the PR with a short list: an attached plan saying 0 to destroy, a verified mapping, comments with the date and the reason, and the refactoring kept separate from the functional change.

That is the end of module 3, and the end of the phase in which EcoMarket was a one-person project. The state is no longer a file on a laptop: it lives in a shared, encrypted, versioned backend, protected by a lock that stops two deployments trampling each other; you know what it holds, how to detect and resolve drift, how to inspect it and how to operate it with the terraform state commands without wrecking anything; and, as of today, you know how to reorganise the code without reorganising costing a single destruction. That last piece is what qualifies you for what comes next: in module 4, Terraform Modules, you are going to take EcoMarket's configuration — which by now is a main.tf doing far too many things — and split it into reusable network, application and data modules, with their interface of variables and outputs, their versioning and their publication. Moving resources inside modules is exactly what you have just learnt to do without breaking anything, so you will start Introduction to Modules with the safety net already in place.

© Copyright 2026. All rights reserved