nerdexam
HashiCorp

TA-002-P · Question #143

You want to use different AMI images for different regions and for the purpose you have defined following code block. 1. variable "images" 2. { 3. type = "map" 4. 5. default = { 6. us-east-1 =…

The correct answer is A. var.images["us-west-1"]. To select a specific AMI image from the images map variable, you must access it by its corresponding string key, such as us-west-1.

Understand Terraform basics

Question

You want to use different AMI images for different regions and for the purpose you have defined following code block. 1. variable "images" 2. { 3. type = "map" 4. 5. default = { 6. us-east-1 = "image-1234" 7. us-west-2 = "image-4567" 8. us-west-1 = "image-4589" 9. } 10. } What of the following approaches needs to be followed in order to select image-4589?

Options

  • Avar.images["us-west-1"]
  • Bvar.images[3]
  • Cvar.images[2]
  • Dlookup(var.images["us-west-1"]

How the community answered

(39 responses)
  • A
    90% (35)
  • B
    3% (1)
  • C
    5% (2)
  • D
    3% (1)

Why each option

To select a specific AMI image from the `images` map variable, you must access it by its corresponding string key, such as `us-west-1`.

Avar.images["us-west-1"]Correct

Given the `images` variable is a map with region names as keys and image IDs as values, you select 'image-4589' by accessing the map with its key, `us-west-1`, using the syntax `var.images["us-west-1"]`.

Bvar.images[3]

Terraform maps are accessed by their string keys, not by numerical indices like `[3]` as if it were a list.

Cvar.images[2]

Similar to option B, maps are not indexed numerically, so `[2]` is an incorrect way to access elements.

Dlookup(var.images["us-west-1"]

The `lookup` function is used to retrieve values from a map, but the syntax provided is incomplete and incorrect; it's missing the map and a default value, and direct map access is simpler.

Concept tested: Accessing map variables in Terraform

Source: https://developer.hashicorp.com/terraform/language/expressions/variables#accessing-map-elements

Topics

#Terraform variables#Map data type#HCL syntax#Variable access

Community Discussion

No community discussion yet for this question.

Full TA-002-P Practice