for_each Is Not a Loop: It’s Terraform’s Identity Mechanism

Terraform’s for_each is often explained as a looping feature. That description is incomplete.

for_each is an identity mechanism.

When you use count, Terraform tracks resources by position. If the list changes, positions shift. When positions shift, addresses change. When addresses change, Terraform recreates infrastructure. That is not randomness. It is deterministic state tracking.

for_each binds each resource instance to a key. That key becomes part of the state address. If the structure changes, only the affected key changes. Identity remains isolated.

In this lesson, we break down:

  • How Terraform constructs resource addresses
  • Why positional indexing causes unintended recreation cycles
  • Why renaming a key is a lifecycle event
  • How deterministic address resolution reduces volatility

The core chain is simple:

key → address → tracking → lifecycle

If you want stable infrastructure, you must understand how identity is encoded in state.

This lesson focuses on mechanism, not syntax.

https://youtu.be/o7WL4osygnA