Terraform Associate 004 ยท Dynamic configuration
count and for_each: multiple instances from one block
Creating multiple instances, count.index vs each.key/each.value, address forms, why for_each is safer for reordering (4e).
Key points
- count takes a whole number and gives each instance count.index (starting at 0); instances are addressed as type.name[0]. for_each takes a map or a set of strings and gives each.key and each.value; instances are addressed as type.name["key"].
- You cannot use both in one block.
- Prefer for_each when instances differ, because keys stay stable when items are added or removed, while count indexes shift.
Source: https://developer.hashicorp.com/terraform/language/meta-arguments/for_each
Practice questions
What is the value of count.index for the first instance created by a resource with count = 3?
- 0
- 1
- 3
- It has no index until apply
Show answer
Answer: A. 0
Indexes start at 0, so the instances are 0, 1 and 2. The first instance is aws_instance.x[0].
Which values can be passed to for_each directly?
- A map of objects
- A set of strings
- toset(var.name_list)
- A plain list of strings
- The number 3
Show answer
Answer: A. A map of objects, B. A set of strings, C. toset(var.name_list)
for_each accepts a map or a set of strings. A list of strings is not converted implicitly, so it must be wrapped in toset(). A plain number is the domain of count.
True or false: a resource block can set both count and for_each to build a grid of instances.
Show answer
Answer: False
False. The two meta-arguments cannot be combined in one block. To build a grid, flatten the combinations into one map or set with a for expression and use for_each.
Practice 8 questions on this topic in Bitzu
Short lessons, instant explanations and spaced review of what you get wrong. Free on iOS and Android.
