TA-002-P · Question #191
Refer to the following terraform variable definition: variable "track_tag" { type = list default = ["data_ec2","integration_ec2","digital_ec2"]} track_tag = { Name = element(var.track_tag,count.index)
The correct answer is B. digital_ec2. The Terraform element() function retrieves a list item by zero-based index, so element(var.track_tag, 2) returns the third element.
Question
Refer to the following terraform variable definition:
variable "track_tag" { type = list default = ["data_ec2","integration_ec2","digital_ec2"]} track_tag = { Name = element(var.track_tag,count.index)} If count.index is set to 2, which of the following values will be assigned to the name attribute of track_tag variable?
Options
- Aintegration_ec2
- Bdigital_ec2
- Ctrack_tag
- Ddata_ec2
How the community answered
(25 responses)- A8% (2)
- B72% (18)
- C16% (4)
- D4% (1)
Why each option
The Terraform `element()` function retrieves a list item by zero-based index, so `element(var.track_tag, 2)` returns the third element.
`integration_ec2` is at index 1, not index 2, so it would only be returned when `count.index` equals 1.
The list `["data_ec2","integration_ec2","digital_ec2"]` uses zero-based indexing: index 0 is `data_ec2`, index 1 is `integration_ec2`, and index 2 is `digital_ec2`. The `element()` function returns the item at the specified index, so `count.index = 2` yields `digital_ec2`.
`track_tag` is the variable name itself, not a value stored in the list; `element()` returns list contents, not the variable identifier.
`data_ec2` is at index 0, not index 2, so it would only be returned when `count.index` equals 0.
Concept tested: Terraform element() function with list indexing
Source: https://developer.hashicorp.com/terraform/language/functions/element
Topics
Community Discussion
No community discussion yet for this question.