TA-002-P · Question #38
You have declared a variable called var.list which is a list of objects that all have an attribute id. Which options will produce a list of the IDs? (Choose two.)
The correct answer is A. { for o in var.list : o => o.id } B. var.list[*].id. This question asks for valid Terraform expressions to extract the id attribute from a list of objects, and both splat expressions and for expressions are common ways to achieve this.
Question
You have declared a variable called var.list which is a list of objects that all have an attribute id. Which options will produce a list of the IDs? (Choose two.)
Options
- A{ for o in var.list : o => o.id }
- Bvar.list[*].id
- C[ var.list[*].id ]
- D[ for o in var.list : o.id ]
How the community answered
(23 responses)- A83% (19)
- C13% (3)
- D4% (1)
Why each option
This question asks for valid Terraform expressions to extract the `id` attribute from a list of objects, and both splat expressions and `for` expressions are common ways to achieve this.
The expression `{{ for o in var.list : o => o.id }}` uses a `for` loop within an interpolation context to iterate through the list of objects, where `o => o.id` transforms each object `o` into its `id` attribute, resulting in a list of these IDs.
The splat expression `var.list[*].id` is an idiomatic Terraform syntax that extracts the `id` attribute from every object in the `var.list`, effectively producing a list of all the extracted IDs.
The expression `[ var.list[*].id ]` incorrectly wraps the result of the splat expression in another list, leading to a list containing a single element which is itself the list of IDs, rather than a simple list of IDs.
While `[ for o in var.list : o.id ]` is a technically valid and common HCL `for` expression to produce a list of IDs, it is not selected as a correct answer in this specific question's context where other options are designated.
Concept tested: Terraform list iteration and attribute extraction
Source: https://developer.hashicorp.com/terraform/language/expressions/splat-expressions
Topics
Community Discussion
No community discussion yet for this question.