HashiCorp Certified: Terraform Associate free question 6 / 10 · Domain 4: Terraform configuration
resource "aws_instance" "web" uses for_each over a map of three names. A colleague wants all the instance ids collected with a splat expression. What does the references page recommend?
- Write aws_instance.web[*].id, since a splat works on the map of instances.
- Write values(aws_instance.web)[*].id, since a splat needs a list to work on.
- Write aws_instance.web[0].id, since each for_each instance has an index.
- Write aws_instance.web.id, since for_each instances merge into one object.
Show the answer and explanation
Answer: B
Why this is correct
The references page explains that when a resource has the for_each argument set, the resource itself becomes a map of instance objects rather than a single object, and attributes of instances must be specified by key or accessed with a for expression. It then points out that splat expressions are not directly applicable to resources managed with for_each, because splat expressions must act on a list value. However, you can use the values() function to extract the instances as a list and use that list value in a splat expression, as in values(aws_instance.example)[].id. A single instance is reached by its key, for example aws_instance.example["a"].id, where the key is a value from the for_each collection.
Why the other options are wrong
"Write aws_instance.web.id, since for_each instances merge into one object." … With for_each set, the resource becomes a map of instance objects rather than a single object, and attributes of instances must be specified by key or reached with a for expression.
"Write aws_instance.web[0].id, since each for_each instance has an index." … for_each instances are addressed by key. The resource address reference shows them as ["INDEX"] with an alphanumerical key; a numeric index such as [0] belongs to count.
"Write aws_instance.web[].id, since a splat works on the map of instances." … The page says splat expressions are not directly applicable to resources managed with for_each, because splat expressions must act on a list value, and a for_each resource is a map.
for_each makes a map
A for_each resource is a map keyed by the collection. Use ["key"] for one instance, or values() before [] for a list of all of them.