Practical technical guides / Core IT: cloud infrastructure

Move OpenTofu Resources From count to for_each Without Recreating Them

Switching count to for_each destroys every instance unless moved blocks map each index to its key. Measured on OpenTofu 1.13.11, with a plan gate script.

By Sandeep Belgavi · Published 2026-12-02

count to for_each without replacement
Original explanatory diagram; synthetic values where shown.

Switching count to for_each destroys every instance unless moved blocks map each index to its key. Measured on OpenTofu 1.13.11, with a plan gate script.

A list index is not an identity

Many OpenTofu and Terraform configurations start with count over a list: one storage bucket per environment, one queue per team, one DNS record per host name. It works until someone removes an item from the middle of the list. Resources created with count are addressed by position, resource[0], resource[1] and so on, and their identity in state is that number. Remove the second item and every later item shifts down one position. The tool then sees that resource[1] now has the configuration that resource[2] used to have, and plans to change or replace it, and it plans to destroy the last index because it no longer exists.

for_each over a set or map addresses each instance by a key you choose, so removing one key affects only that instance. The OpenTofu documentation for count makes the same recommendation: count is appropriate when instances are almost identical, and when some arguments need distinct values that cannot be derived from an integer, for_each is safer. The difficulty is getting from one to the other on a configuration that already has resources in state, without destroying them.

Measured: what the plan does at each step

The local probe ran a small configuration through OpenTofu 1.13.11, using the built-in terraform_data resource so that no cloud provider or credentials are involved. Each instance stores a shelf name for a Belgavi's Book Store warehouse and sets triggers_replace to that name. That attribute forces replacement when its value changes, which stands in for the many real resource arguments that cannot be updated in place, such as a bucket name. The shelves are alpha, beta and gamma. After each change the probe ran tofu plan with a saved plan file and read the actions from tofu show -json.

StepPlan
count over three shelves, then remove beta from the listindex 1 replaced (delete then create), index 2 destroyed: 1 to add, 2 to destroy
Switch to for_each, no moved blocksindexes 0, 1 and 2 destroyed; keys alpha, beta and gamma created
Switch to for_each with moved blocks, beta and gamma swapped by mistakealpha moved with no change; beta and gamma moved and then replaced
Switch to for_each with moved blocks in the right orderthree moves, no other changes
After that apply, remove betaonly the beta key destroyed

The first row is the problem in one line: removing one shelf replaced a different shelf. The second row is the trap: the obvious refactor, changing count to for_each and nothing else, destroys and recreates everything, because OpenTofu has no way to know that index 0 and key alpha are the same object. The fourth row is the goal. The third row is the most dangerous, because a plan that mentions moves looks like a safe refactor at a glance, and it still replaced two resources.

The refactor in code

The starting configuration:

variable "shelves" {
  type = list(string)
}

resource "terraform_data" "shelf" {
  count            = length(var.shelves)
  input            = var.shelves[count.index]
  triggers_replace = var.shelves[count.index]
}

The new configuration keys each instance by its name and records where each existing instance came from:

resource "terraform_data" "shelf" {
  for_each         = toset(var.shelves)
  input            = each.key
  triggers_replace = each.key
}

moved {
  from = terraform_data.shelf[0]
  to   = terraform_data.shelf["alpha"]
}

moved {
  from = terraform_data.shelf[1]
  to   = terraform_data.shelf["beta"]
}

moved {
  from = terraform_data.shelf[2]
  to   = terraform_data.shelf["gamma"]
}

A moved block tells OpenTofu that the object at the old address is now at the new address. During planning it updates the address in state first and then compares the configuration as usual. If the configuration at the new address matches what the object already has, the result is a move and nothing else. If it does not, as in the swapped case, the move happens and then the normal rules apply, which in this example means replacement.

The mapping must come from state, not from the current list. Run tofu state list and tofu state show for each index and write down which name each index actually holds. If the list was edited without an apply, or if someone applied from an older branch, position and name may already disagree.

Gate the refactor on the plan, not on review

Reading the plan output by eye works for three resources and fails for three hundred. Save the plan and check it with a script that fails if any action other than a move with no change appears.

import json
import subprocess
import sys

def check_refactor_plan(plan_file: str) -> list[str]:
    """Return every resource change that is not a pure move or no-op."""
    shown = subprocess.run(["tofu", "show", "-json", plan_file],
                           capture_output=True, text=True, check=True)
    plan = json.loads(shown.stdout)
    problems = []
    for change in plan.get("resource_changes", []):
        actions = change["change"]["actions"]
        if actions != ["no-op"]:
            problems.append(f"{change['address']}: {'+'.join(actions)}")
    return problems

if __name__ == "__main__":
    bad = check_refactor_plan(sys.argv[1])
    print("\n".join(bad) or "only moves")
    sys.exit(1 if bad else 0)

In the swapped case the script prints two lines, one for beta and one for gamma, each with delete+create, and exits with 1. For the correct mapping it prints only moves. The JSON plan also records each instance's previous_address, so the same script can assert that the number of moves equals the number of instances you intended to move.

Keep a refactor plan separate from other changes. If the same pull request also changes a tag, the gate has to tell expected updates from unexpected ones, and a reviewer has more to read. Move first, apply, then change behaviour in the next plan.

Migration steps

  1. Freeze changes to the list for the duration of the migration, so the state and the configuration agree on positions.
  2. List the current instances from state and record the index-to-key mapping for each.
  3. Change count to for_each, generate one moved block per instance from the recorded mapping, and run a plan saved to a file.
  4. Run the gate. It must report only moves. Fix the mapping until it does.
  5. Apply the saved plan, not a new plan, so what was checked is what runs.
  6. Keep the moved blocks. The OpenTofu refactoring guide recommends retaining them for as long as any workspace or caller of a shared module might still have the old addresses in state. Removing them early turns the next plan in an old workspace back into the destroy-and-create of row two.
  7. Remove an item from the list in a later change and confirm that only its key is destroyed.

For modules used in several workspaces, every workspace runs the same moved blocks on its own state. Workspaces whose lists were in different orders need different mappings, so moved blocks written for one ordering do not fit them. In that case, prefer a per-workspace tofu state mv run under the same plan gate, or derive the keys so that each workspace's existing order is preserved.

Failure modes

  • Keys that are not stable. A for_each key derived from a value that can change, such as a display name, has the same problem as an index. Use an identifier that will not be edited.
  • Keys known only after apply. for_each keys must be known during planning. Keys computed from attributes of resources that do not exist yet cause a plan error.
  • Duplicates in the list. toset removes them, so two indexes can collapse into one key; one of them is destroyed. Check for duplicates before converting.
  • Data sources and other resources in the same plan. The gate above flags any action that is not a no-op, including reads of data sources whose values are not known until apply. Filter by resource address prefix if the module contains them, rather than loosening the rule.
  • Apply without the gate. The saved plan is the contract. A new plan generated at apply time may include drift that the gate never saw.

When you do not need this

If the list never changes in the middle, for example a fixed count of identical worker instances that only grows or shrinks at the end, count is fine and simpler. If the resources are disposable and recreating them is cheap and expected, the destroy-and-create plan may be acceptable without moved blocks. The migration is worth its care for resources that hold data or identity: buckets, databases, queues, DNS records and IAM principals.

How to verify it

The companion example tofu_count_to_for_each downloads OpenTofu 1.13.11 with a pinned checksum, runs the five steps above in a scratch directory with terraform_data, and asserts each plan summary, including the failure of the swapped mapping. Run your own migration the same way: a scratch copy of the state, a saved plan, the gate, and only then the real apply.

Primary references and authorship

Sources checked 2026-12-02. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/tofu_count_to_for_each. Views are my own and do not represent any employer, past or present.