Terraform count to for_each Converter

Rewrite count as for_each and get the moved blocks the change requires. Without them the refactor destroys every existing instance and creates replacements.

Paste below, or drop a file anywhere on this panel

Or drop a file anywhere on this panel. Nothing is uploaded: the analysis runs in this tab.

The answer appears here

Paste on the left and press Convert. Nothing leaves this tab.

Examples

Real input you can load into the tool above. Each one shows a different thing going wrong, because that is what the tool is for.

A count over a list of zones

Converts, and every instance address changes, so moved blocks are required

resource "aws_subnet" "private" {
  count             = length(var.availability_zones)
  availability_zone = var.availability_zones[count.index]
}

A conditional count

Deliberately not converted: this is the one count that beats for_each

resource "aws_instance" "bastion" {
  count         = var.enable_bastion ? 1 : 0
  instance_type = "t3.micro"
}

A bare number

Nothing to key by, so converting would mean inventing keys that carry no information

resource "aws_instance" "web" {
  count = 3
}

Common mistakes

These are the ones that fail silently. The config is accepted, nothing raises an error, and the consequence arrives later.

  1. Converting count to for_each and applying without moved blocks

    Every instance address changes, so Terraform destroys all the existing instances and creates replacements. The plan shows it and it is easy to approve while thinking of the change as a refactor.

    Instead:Write one moved block per instance, then plan and confirm zero changes. If the plan shows destroys, stop: the moved blocks are wrong.

  2. Converting a conditional count

    count = condition ? 1 : 0 becomes a set that is empty or has one member, which is more code, less readable, and adds a key nobody uses.

    Instead:Leave it as a count. That is the case count is genuinely better at.

  3. Wrapping a list of objects in toset

    A set of objects cannot be keyed usefully, and duplicates collapse silently, so you get fewer resources than the count produced with nothing to say why.

    Instead:Build the map explicitly: for_each = { for item in var.items : item.name => item }.

The rewrite is easy and the state consequence is the whole job

count instances live at [0] and [1]. for_each instances live at their key. Terraform sees one set of addresses disappear and another appear, and its default response is destroy and create.

Every instance address changes

That is the entire risk. A configuration that converts cleanly and applies without moved blocks will destroy and recreate every instance the resource manages. On a subnet that is disruptive; on a database or a volume it is data loss. The plan says so plainly, which is why the rule is to read it and stop if it shows a destroy.

for_each keys are stable and count indices are not

This is the reason to convert at all. Remove the second element of a three-element count and Terraform renumbers the third, so it destroys and recreates something you did not touch. A for_each keyed by a region name or an environment leaves the others alone, because identity comes from the key rather than from position.

The conditional count is the one to keep

count = var.enabled ? 1 : 0 is create-or-do-not, and for_each expresses it as a set that is empty or has one member. That is longer, harder to read, and gives the instance a key nobody needs. This page deliberately refuses to convert it.

toset discards order and collapses duplicates

A set has neither. A list with a repeated element produces fewer instances than the count did, silently, and nothing reports the difference. For a list of objects, toset will not do at all: build the map yourself with a for expression and choose a key that means something.

Indexed references elsewhere break too

aws_subnet.private[0].id has no meaning once the resource is keyed, and the error appears in whichever file holds the reference rather than in the file that changed. Terraform says the resource has no index, which does not mention that the collection type changed.

moved blocks need Terraform 1.1

Before that, the only route is terraform state mv: one person, one state, no plan, and nothing recorded in the repository. Everyone else's state has to be moved by hand the same way. A moved block is reviewed in a pull request and applies everywhere, including in CI.

More terraform tools

Terraform Validator & Formatter Does it parse, and is it formatted? Terraform dynamic Block Generator It is ingress.value, not each.value Terraform check and precondition Generator A failed check does not stop the apply Terraform variables.tf Generator From the var. references you already wrote Terraform Unused Declaration Linter Dead variables, locals and data sources Terraform Atlantis YAML Generator when_modified misses your modules Terraform Function Tester and HCL Console terraform console, in a tab Terraform for Expression Tester Where do the keys collide? Terraform Interpolation Tester null becomes an empty string Terraform templatefile Tester Render it before you apply it Terraform Resource Count Calculator How many objects, not how many blocks Terraform moved Block Generator Rename without destroying Terraform state mv Command Builder No plan, no undo Terraform target Flag Builder And why to stop using it Terraform outputs.tf Generator Outputs are not sensitive by default Terraform Remote State Data Source Generator It grants read of the whole state Terraform Provider Block Generator docker is not hashicorp/docker Terraform .gitignore Generator and Checker .terraform* eats the lock file Terraform to OpenTofu Migration Checker The state is the part to watch Terraform tfvars to JSON Converter The JSON file wins Terraform Version Constraint Parser What ~> actually allows Terraform Resource Address Parser Quote it before the shell eats it Terraform cidrsubnet Calculator newbits is added, not the target Terraform Import Block Generator The id is not the name Terraform Lock File Viewer Why CI fails and your laptop does not Terraform Variables Checker A missing value hangs CI Terraform tfvars to Env Vars Converter Lists and maps have to be JSON Terraform Deprecated Syntax Checker What a current Terraform rejects Terraform State File Viewer Read it without uploading it Terraform Plan JSON Viewer It is not redacted Terraform HCL to JSON Converter And what the conversion loses Terraform Module Source Validator version only works for the registry Terraform Backend Config Decoder Is state actually locked? Terraform Naming Convention Validator A hyphen makes a resource unreferenceable

Elsewhere on the site