Switching count to for_each on Live Resources? Write the moved Blocks First

On live resources, a count-to-for_each refactor is a destroy and create unless you tell Terraform otherwise.

  • Terraform
  • Refactoring
  • Private endpoints

Moving a resource from count to for_each is a good refactor: keys are stable, so removing one item no longer shifts every item after it. But on live resources it has a nasty side effect.

Terraform tracks resources by address. azurerm_private_endpoint.this[0] and azurerm_private_endpoint.this["blob"] are different addresses, so after the refactor Terraform sees one resource to destroy and a new one to create. For a private endpoint in production, that's an outage.

Tell Terraform they're the same resource:

moved {
  from = azurerm_private_endpoint.this[0]
  to   = azurerm_private_endpoint.this["blob"]
}

moved {
  from = azurerm_private_endpoint.this[1]
  to   = azurerm_private_endpoint.this["file"]
}

Then re-plan. A correct refactor shows moves and no destroys. If you see a single destroy you didn't expect, stop: a key doesn't match what's in state.

Read every destroy in a plan, every time. Refactors are where they hide.

Get in touch