nerdexam
HashiCorp

TA-002-P · Question #235

Consider the following Terraform 0.12 configuration snippet: 1. variable "vpc_cidrs" { 2. type = map 3. default = { 4. us-east-1 = "10.0.0.0/16" 5. us-east-2 = "10.1.0.0/16" 6. us-west-1 =…

The correct answer is C. var.vpc_cidrs["us-east-1"]. Map variables in Terraform are accessed using var.<name>["<key>"] syntax, requiring the var. prefix and a string key in brackets.

Read, generate, and modify configuration

Question

Consider the following Terraform 0.12 configuration snippet: 1. variable "vpc_cidrs" { 2. type = map 3. default = { 4. us-east-1 = "10.0.0.0/16" 5. us-east-2 = "10.1.0.0/16" 6. us-west-1 = "10.2.0.0/16" 7. us-west-2 = "10.3.0.0/16" 8. } 9. } 10. 11. resource "aws_vpc" "shared" { 12. cidr_block = _____________ 13. } How would you define the cidr_block for us-east-1 in the aws_vpc resource using a variable?

Options

  • Avar.vpc_cidrs.0
  • Bvpc_cidrs["us-east-1"]
  • Cvar.vpc_cidrs["us-east-1"]
  • Dvar.vpc_cidrs[0]

How the community answered

(17 responses)
  • A
    6% (1)
  • C
    94% (16)

Why each option

Map variables in Terraform are accessed using `var.<name>["<key>"]` syntax, requiring the `var.` prefix and a string key in brackets.

Avar.vpc_cidrs.0

`var.vpc_cidrs.0` uses numeric dot notation intended for list or tuple types, not map types that use string keys.

Bvpc_cidrs["us-east-1"]

`vpc_cidrs["us-east-1"]` is missing the required `var.` prefix and would cause an unknown identifier error.

Cvar.vpc_cidrs["us-east-1"]Correct

Map values in Terraform are accessed using bracket notation with the key as a string, so `var.vpc_cidrs["us-east-1"]` correctly retrieves the CIDR block for the `us-east-1` key. The `var.` prefix is mandatory to reference input variables, and the string key must match exactly as defined in the map.

Dvar.vpc_cidrs[0]

`var.vpc_cidrs[0]` uses a numeric index which is invalid for a map type; maps require string keys, not integer positions.

Concept tested: Accessing map variable values in Terraform

Source: https://developer.hashicorp.com/terraform/language/expressions/types#maps-objects

Topics

#Terraform variables#Map type#Accessing map elements#HCL syntax

Community Discussion

No community discussion yet for this question.

Full TA-002-P Practice