-
-
Save tracphil/480c43014b07b5e0f332114f4ae12059 to your computer and use it in GitHub Desktop.
Terraform 12 - for_each with list of objects
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
/* | |
Usage: | |
$ tfenv install 0.12.19 | |
$ tfenv use 0.12.19 | |
$ terraform init | |
$ terraform plan | |
$ terraform apply -auto-approve | |
$ terraform destroy | |
Reference: https://github.com/hashicorp/terraform/issues/22516 | |
*/ | |
locals { | |
dynamic_self_sg = [ | |
{ | |
type = "ingress" | |
from_port = 22 | |
to_port = 22 | |
protocol = "tcp" | |
}, | |
{ | |
type = "ingress" | |
from_port = 80 | |
to_port = 80 | |
protocol = "tcp" | |
}, | |
] | |
groups_map = [ | |
{ | |
name = "groupe1@renault.com" | |
role = "roles/editor" | |
}, | |
{ | |
name = "groupe2@renault.com" | |
role = "roles/viewer" | |
}, | |
{ | |
name = "groupe2@renault.com" | |
role = "project/myCustomRole" | |
}, | |
{ | |
name = "groupe1@renault.com" | |
role = "roles/bigquery.admin" | |
}, | |
] | |
} | |
resource "null_resource" "dynamic_self" { | |
/* | |
The following use of for_each fails with: | |
Error: Invalid for_each argument | |
The given "for_each" argument value is unsuitable: the "for_each" argument | |
must be a map, or set of strings, and you have provided a value of type tuple. | |
for_each = [ | |
for s in local.dynamic_self_sg : { | |
type = s.type | |
from_port = s.from_port | |
to_port = s.to_port | |
protocol = s.protocol | |
} | |
if length(local.dynamic_self_sg) != 0 | |
] | |
*/ | |
for_each = { | |
for s in local.dynamic_self_sg : "${s.type} ${s.protocol}:${s.from_port}-${s.to_port}" => s | |
} | |
provisioner "local-exec" { | |
command = "echo ${each.key}" | |
} | |
} | |
resource "null_resource" "standard_roles" { | |
# Extract mappings between groups and standard roles | |
for_each = { | |
for mapping in local.groups_map : | |
"${mapping.name}:${mapping.role}" => mapping | |
if substr(trimspace(mapping.role), 0, 6) == "roles/" | |
} | |
provisioner "local-exec" { | |
command = "echo Assign standard role ${each.value.role} to ${each.value.name}" | |
} | |
} | |
resource "null_resource" "custom_roles" { | |
# Extract mappings between groups and project-level custom roles | |
for_each = { | |
for mapping in local.groups_map : | |
"${mapping.name}:${mapping.role}" => mapping | |
if substr(trimspace(mapping.role), 0, 8) == "project/" | |
} | |
provisioner "local-exec" { | |
command = "echo Assign custom role ${each.value.role} to ${each.value.name}" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment