Bitzu

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

Single choice

What is the value of count.index for the first instance created by a resource with count = 3?

  1. 0
  2. 1
  3. 3
  4. 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].

Select all that apply

Which values can be passed to for_each directly?

  1. A map of objects
  2. A set of strings
  3. toset(var.name_list)
  4. A plain list of strings
  5. 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

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.

Download on the App StoreGet it on Google Play

More Terraform Associate 004 topics in this module