Cloud/Terraform/ForLoop
Loop over LIST/MAP gen MAP
- Loop over a list and output a map
{for <ITEM> in <LIST> : <OUTPUT_KEY> => <OUTPUT_VALUE>}
- Loop over a map and output a map
{for <KEY>, <VALUE> in <MAP> : <OUTPUT_KEY> => <OUTPUT_VALUE>}
Loop over LIST/MAP gen LIST
[for <ITEM> in <LIST> : <OUTPUT>]
[for <KEY>, <VALUE> in <MAP> : <OUTPUT>]
Merge List of Map(dict) into single MAP
* https://developer.hashicorp.com/terraform/language/functions/merge
* e.g. 1
> merge([{a="b", c="d"}, {}, {e="f", c="z"}]...) { "a" = "b" "c" = "z" "e" = "f" }
e.g.2 notice the magic "..." passed to merge
hosts = merge(( [for k, v in var.config : { for host in v.backend_hosts : "${k}_${host}" => host } ] )...)
Flatten
e.g.
> flatten([[["a", "b"], []], ["c"]]) ["a", "b", "c"]
Nested for loops
nest
locals { expanded_access = flatten([ for k, v in var.access : [ for index, role in v.role_names : { key = "${k}-${replace(role, " ", "_")}" value = merge(v, { role = role }, {description = try(v.descriptions_role_assignment[index], null)},) } ] ]) }
use
for_each = { for item in local.expanded_access : item.key => item.value }
Variable validation on list
Uniq
- distinct(["a","a"] = ["a"]