How to Use Map Variable in Terraform: Syntax and Example
In Terraform, you define a
map variable using the variable block with type = map(string) or other types. You can access map values by their keys using var.variable_name["key"]. This lets you organize related values in key-value pairs for flexible configuration.Syntax
A map variable in Terraform is declared inside a variable block with type = map(TYPE), where TYPE is the type of the values (commonly string).
You assign the map values when calling Terraform or in a terraform.tfvars file.
Access map values using var.variable_name["key"].
terraform
variable "example_map" { type = map(string) description = "A map of strings" default = { key1 = "value1" key2 = "value2" } } # Access example: # var.example_map["key1"] # returns "value1"
Example
This example shows how to define a map variable and use it to create AWS tags for a resource.
terraform
variable "tags" { type = map(string) default = { Environment = "dev" Project = "demo" } } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" tags = var.tags }
Output
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
# The AWS instance will have tags Environment=dev and Project=demo
Common Pitfalls
Common mistakes when using map variables include:
- Not specifying the
typeasmap(TYPE), which can cause unexpected errors. - Accessing keys that do not exist, which leads to runtime errors.
- Using incorrect syntax for accessing map values, such as missing quotes around keys.
Always validate your keys exist before accessing or provide defaults.
terraform
variable "colors" { type = map(string) default = { red = "#ff0000" green = "#00ff00" } } # Wrong access (missing quotes): # var.colors[red] # Error: red is not defined # Correct access: # var.colors["red"] # returns "#ff0000"
Quick Reference
| Concept | Example | Description |
|---|---|---|
| Declare map variable | variable "map_var" { type = map(string) } | Defines a map variable with string values |
| Assign default | default = { key1 = "val1" } | Sets default key-value pairs |
| Access value | var.map_var["key1"] | Gets value for key1 |
| Use in resource | tags = var.map_var | Pass map variable to resource attribute |
Key Takeaways
Declare map variables with type = map(TYPE) to organize key-value pairs.
Access map values using var.variable_name["key"] with quotes around keys.
Always specify the map type to avoid errors and improve clarity.
Check keys exist before accessing to prevent runtime errors.
Use map variables to simplify passing multiple related values to resources.