Skip to content

Instantly share code, notes, and snippets.

@richlamdev
Forked from NosearY/locals.tf
Created April 28, 2023 23:17
Show Gist options
  • Save richlamdev/1d49401d35faa2c276d8010ab53f3c25 to your computer and use it in GitHub Desktop.
Save richlamdev/1d49401d35faa2c276d8010ab53f3c25 to your computer and use it in GitHub Desktop.
Flatten a map in terraform
locals {
nested_map = {
"app1" = {
"port" = 80
"image" = "nginx:latest"
"url" = [
"https://www.google.com",
"https://www.github.com",
"https://www.hashicorp.com"
]
},
"app2" = {
"port" = 8080
"image" = "tomcat:latest",
"url" = [
"https://www.google.com",
"https://www.github.com",
"https://www.hashicorp.com"
]
}
}
flattened_map = flatten([
for app_name, app_details in local.nested_map :
[
for url in app_details["url"] :
{ app_name = "${app_name}", url = "${url}", port = app_details["port"], image = app_details["image"] }
]
])
}
/*
$ terraform console <<<local.flattened_map
[
{
"app_name" = "app1"
"image" = "nginx:latest"
"port" = 80
"url" = "https://www.google.com"
},
{
"app_name" = "app1"
"image" = "nginx:latest"
"port" = 80
"url" = "https://www.github.com"
},
{
"app_name" = "app1"
"image" = "nginx:latest"
"port" = 80
"url" = "https://www.hashicorp.com"
},
{
"app_name" = "app2"
"image" = "tomcat:latest"
"port" = 8080
"url" = "https://www.google.com"
},
{
"app_name" = "app2"
"image" = "tomcat:latest"
"port" = 8080
"url" = "https://www.github.com"
},
{
"app_name" = "app2"
"image" = "tomcat:latest"
"port" = 8080
"url" = "https://www.hashicorp.com"
},
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment