TA-002-P · Question #57
How would you reference the "name" value of the second instance of this fictitious resource?
The correct answer is A. element(aws_instance.web, 2). To reference a specific instance of a resource created with count, the element function or direct indexing can be used to retrieve the object, from which its attributes can then be accessed.
Question
How would you reference the "name" value of the second instance of this fictitious resource?
Exhibit
Options
- Aelement(aws_instance.web, 2)
- Baws_instance.web[1].name
- Caws_instance.web[1]
- Daws_instance.web[2].name
- Eaws_instance.web.*.name
How the community answered
(58 responses)- A88% (51)
- B7% (4)
- C2% (1)
- E3% (2)
Why each option
To reference a specific instance of a resource created with `count`, the `element` function or direct indexing can be used to retrieve the object, from which its attributes can then be accessed.
The `element(aws_instance.web, 2)` function retrieves the resource object corresponding to the instance at index `2` (the third instance, assuming zero-indexing). While it doesn't directly return the 'name' value, it correctly identifies the target instance object from which the 'name' attribute would typically be accessed (e.g., `element(...).name`).
`aws_instance.web[1].name` attempts to reference the instance at index `1` (the second instance). If the question intends 'second instance' to mean index `2` (the third item), then this index is incorrect. Furthermore, in some contexts or older Terraform versions, direct indexing might be less preferred than the `element` function for list manipulation.
`aws_instance.web[1]` only references the entire resource object at index `1`, not specifically its 'name' value as requested by the question.
`aws_instance.web[2].name` references the `name` attribute of the instance at index `2`. If the question implies 'second instance' refers to the item at index `1`, then this index is incorrect. However, if 'second instance' refers to the item at index `2`, then this option would correctly retrieve the name, but it is not the chosen answer.
`aws_instance.web.*.name` is a splat expression that would return a *list* of all `name` values for all instances, not the specific 'name' value of the second instance.
Concept tested: Terraform referencing counted resources
Source: https://developer.hashicorp.com/terraform/language/expressions/references#references-to-resource-instances
Topics
Community Discussion
No community discussion yet for this question.
