Terraform List Of Maps
Let's go one step further: A list of maps. Again in main.tf in the root module
List of Maps we use
variable "LIST_OF_MAPS" {
type = list(map(string))
default = [
{
city = "Amsterdam"
country = "Netherlands"
},
{
city = "New York"
country = "United States of America"
},
{
city = "London"
country = "United Kingdom"
}
]
}
Get 'country' of second element
In Javascript this would be an array of objects, which is very common there.
Suppose we need the country of the second element in the list.
output "LISTMAP_COUNTRY_OF_ELEMENT_2" {
value = var.LIST_OF_MAPS[1].country
}
Output
LISTMAP_COUNTRY_OF_ELEMENT_2 = "United States of America"
Get all Countries, with a for loop
output "LISTMAP_ALL_COUNTRIES_1" {
value = [for i in var.LIST_OF_MAPS: i.country]
}
Output
LISTMAP_ALL_COUNTRIES_1 = [
"Netherlands",
"United States of America",
"United Kingdom",
]
Get all Countries, with a Splat Expression
output "LISTMAP_ALL_COUNTRIES_2" {
value = var.LIST_OF_MAPS.*.country
}
Output
LISTMAP_ALL_COUNTRIES_2 = tolist([
"Netherlands",
"United States of America",
"United Kingdom",
])
Use a Module to handle each element individually
As with the previous examples, here also a Module to handle each element of the List individually
Calling the module from main.tf
module "LIST_OF_MAPS" {
source = "./module_listofmap"
count = length(var.LIST_OF_MAPS)
LISTOFMAP_ELEMENT = var.LIST_OF_MAPS[count.index]
}
Since this is a List, we use the Count again.
Variable passed to the Module is "LISTOFMAP_ELEMENT"
and the value of that variable is each occurrence on the LIST_OF_MAPS variable.
Inside the Module
The module, residing in "module_listofmap" subdirectory in a file called main.tf, has the following code:
variable "LISTOFMAP_ELEMENT" {
type = map(string)
}
output "COUNTRY" {
value = var.LISTOFMAP_ELEMENT.country
}
It receives a variable which is of type Map (of strings), and it sends back to the caller the value of the Country property in that Map.
Back in root module, main.tf
main.tf picks up on that output and sends it back to the screen with an output of its own:
output "ALL_COUNTRIES" {
value = module.LIST_OF_MAPS[*].COUNTRY
}
Output
ALL_COUNTRIES = [
"Netherlands",
"United States of America",
"United Kingdom",
]