nerdexam
HashiCorp

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.

Read, generate, and modify configuration

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)
  • A
    83% (19)
  • C
    13% (3)
  • D
    4% (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.

A{ for o in var.list : o => o.id }Correct

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.

Bvar.list[*].idCorrect

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.

C[ var.list[*].id ]

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.

D[ for o in var.list : o.id ]

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

#HCL Syntax#List Manipulation#For Expressions#Splat Operator

Community Discussion

No community discussion yet for this question.

Full TA-002-P Practice