For_each and stable keys
Give each environment a durable name
In the previous chapter, numbered instances depended on their position. Imagine a small team with a development and a test environment. These are distinct logical members, so use their names as keys instead of assigning numbers. In a disposable local module, the following configuration stores labels in state without provisioning cloud infrastructure. The lab file includes the inherited provisional version pin.
variable "environments" { type = map(string) nullable = false default = { dev = "small" test = "medium" } validation { condition = length(var.environments) <= 5 && alltrue([for k, v in var.environments : v != null]) error_message = "Supply at most five environments with non-null labels." }}
resource "terraform_data" "environment" { for_each = var.environments input = each.value}
output "labels" { value = { for k, item in terraform_data.environment : k => item.output }}With the defaults, expect two addresses: terraform_data.environment["dev"] and terraform_data.environment["test"]. After a successful local apply, the labels output should associate dev with small and test with medium. each.key is the current name and each.value is the associated setting. A map key is the address component; the value is merely configuration data in this example. The variable uses a non-null default when the whole input is null because nullable is false; it rejects null labels through validation. The empty map is allowed.
Read a named instance or the whole map
A reference to this repeated resource is a map of instance objects. Read one by its string key, or use a for expression to select attributes from all instances. These are expressions for the preceding fixture, not standalone files.
terraform_data.environment["dev"].outputkeys(terraform_data.environment){ for k, item in terraform_data.environment : k => item.output }With the default applied fixture, the first is small, the second lists dev and test, and the third produces the labels mapping. If dev is absent, indexing it directly is an error. For an optional key, use a membership test or a deliberately chosen fallback with try. A splat over the resource map is not the appropriate tool; iterate over the map or its values. For a POSIX shell, preserve the inner quotes when inspecting a specific applied instance: terraform state show 'terraform_data.environment["dev"]'. Other shells may require different quoting.
Use a set when the name is the only setting
For a collection of distinct labels without associated settings, a set of strings is enough. Here red appears twice in the source list.
resource "terraform_data" "badge" { for_each = toset(["red", "blue", "red"]) input = each.key}Expect badge["red"] and badge["blue"] only. Conversion to a set removes duplicates and does not preserve list order. In this block each.value would equal each.key. A raw list is not accepted as the repetition argument; choose explicit set conversion when losing duplicates is intentional. A set of objects is not a suitable for_each collection. Do not combine count and for_each on one resource.
Convert records to an identity map
When your input is a list of records, select an identifier that is unique and stable. The display label can change independently of the identifier.
locals { inventory = [ { code = "desk-a", label = "Window" }, { code = "desk-b", label = "Door" } ] by_code = { for item in local.inventory : item.code => item.label }}
resource "terraform_data" "desk" { for_each = local.by_code input = each.value}The expected desk addresses contain desk-a and desk-b. Swapping the list entries leaves their address mapping unchanged. Giving both records the same code makes the object comprehension fail with a duplicate-key error; do not silently discard one. Grouping duplicates with the ellipsis produces grouped values, not separate addresses, and changes the data model. Choose a durable identifier before defining the mapping. See the worksheet for an insertion and duplicate-code check.
Chain two families of resources
The following independent local fixture gives each catalog item a matching receipt. The second resource uses the first resource map directly. This models one-to-one relationships without any external service.
resource "terraform_data" "catalog" { for_each = { north = "N", south = "S" } input = each.value}
resource "terraform_data" "receipt" { for_each = terraform_data.catalog input = each.value.id}The four expected addresses are catalog["north"], catalog["south"], receipt["north"] and receipt["south"]. The catalog IDs need not be known yet for Terraform to determine the receipt addresses. The receipt input can be resolved later because only the keys identify instances. After apply, each receipt input should match its corresponding catalog ID. Do not expect any literal ID to repeat across clean runs. The reference creates a dependency; it does not prescribe alphabetical creation order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
For_each and stable keys — knowledge check
Check keyed identity, collection semantics and safe migration reasoning.
Which address selects the development instance in the map fixture?
How many badge instances result from toset(["red", "blue", "red"])?
What happens if both desk records have the same code in the map comprehension?
Why can the receipt resource chain from the catalog map in a fresh plan?
What does each.value equal when for_each uses a set of strings?