nerdexam
HashiCorp

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.

Read, generate, and modify configuration

Question

How would you reference the "name" value of the second instance of this fictitious resource?

Exhibit

TA-002-P question #57 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)
  • A
    88% (51)
  • B
    7% (4)
  • C
    2% (1)
  • E
    3% (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.

Aelement(aws_instance.web, 2)Correct

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`).

Baws_instance.web[1].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.

Caws_instance.web[1]

`aws_instance.web[1]` only references the entire resource object at index `1`, not specifically its 'name' value as requested by the question.

Daws_instance.web[2].name

`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.

Eaws_instance.web.*.name

`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

#Terraform functions#element function#Resource referencing#List access

Community Discussion

No community discussion yet for this question.

Full TA-002-P Practice