TERRAFORM-ASSOCIATE-004 · Question #261
Consider the following Terraform 0.12 configuration snippet: variable "vpc_cidrs" { type = map default = { us-east-1 = "10.0.0.0/16" us-east-2 = "10.1.0.0/16" us-west-1 = "10.2.0.0/16" us-west-2 = "10
The correct answer is A. var.vpc_cidrs["us-east-1"]. To access a specific value from a map variable in Terraform, you use the var. prefix followed by the variable name and the key in square brackets.
Question
Options
- Avar.vpc_cidrs["us-east-1"]
- Bvar.vpc_cidrs.0
- Cvpc_cidrs["us-east-1"]
- Dvar.vpc_cidrs[0]
How the community answered
(54 responses)- A81% (44)
- B6% (3)
- C11% (6)
- D2% (1)
Why each option
To access a specific value from a map variable in Terraform, you use the `var.` prefix followed by the variable name and the key in square brackets.
To access a specific value within a map variable named `vpc_cidrs`, the correct syntax uses `var.<variable_name>["<key>"]`, making `var.vpc_cidrs["us-east-1"]` the appropriate way to retrieve the CIDR block for that region.
Accessing map elements by numerical index (e.g., `.0`) is not valid for Terraform map types, which require string keys.
Terraform variable references must be prefixed with `var.`, so `vpc_cidrs["us-east-1"]` without the prefix is incorrect syntax.
Accessing map elements by numerical index (e.g., `[0]`) is not valid for Terraform map types, which require string keys.
Concept tested: Accessing Terraform map variable elements
Source: https://developer.hashicorp.com/terraform/language/values/variables#accessing-input-variable-values
Topics
Community Discussion
No community discussion yet for this question.