Terraform Length + Count: The Hidden Trap Most Engineers Miss

Most engineers think count creates resources from a list. It doesn’t. Terraform does not read your list directly. It reads a number, and that number usually comes from length(). The mechanism is simple: collection size becomes a number, and that number becomes the resource count.

This seems safe, but it introduces a hidden risk.

When you use count, Terraform assigns identity based on position, not value. Index 0 is the first resource, index 1 is the second, and so on. That means identity is tied to order, not meaning.

Now remove one item from the middle of your list. Every element after it shifts position. Terraform does not interpret this as the same resources moving. It interprets it as different resources in different slots. The mechanism is positional re-indexing. The outcome is that Terraform may update or replace the wrong resource from your perspective, even though it is behaving correctly from the configuration’s point of view.

This is not a syntax issue. This is an identity problem.

length() controls how many resources exist. count.index controls which resource is which. If the list changes, the identity changes.

That distinction determines whether your infrastructure behaves predictably or silently drifts over time.