Last active
May 29, 2024 15:19
-
-
Save NosearY/0ce0b61b1d4061c916ba1c1cf2122788 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