-
-
Save richlamdev/1d49401d35faa2c276d8010ab53f3c25 to your computer and use it in GitHub Desktop.
Flatten a map in terraform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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