Terraform does not support ‘nested loop’. (i.e. you can only for_each
for one layer of loop).
So what if you have two lists, and you want to create resource for each combination?
Use setproduct
then use for in
expression:
locals {
azure_roles = [
"Virtual Machine Contributor",
"Compute Gallery Image Reader",
]
scopes = [
"path-to-your-subscirption-1",
"path-to-your-subscirption-2",
]
roles_and_scopes = setproduct(local.azure_roles, local.scopes)
// Output of local.roles_and_scopes:
// tolist([
// [
// "path-to-your-subscirption-1",
// "Virtual Machine Contributor",
// ],
// [
// "path-to-your-subscirption-1",
// "Compute Gallery Image Reader",
// ],
// [
// "path-to-your-subscirption-2",
// "Virtual Machine Contributor",
// ],
// [
// "path-to-your-subscirption-2",
// "Compute Gallery Image Reader",
// ],
// ])
role_assignments_to_create = {
for comb in local..roles_and_scopes :
"${comb[0]}:${replace(comb[1], " ", "_")}" => { // So key will be like "path-to-your-subscirption-1:Virtual_Machine_Contributor"
role_definition_name = comb[0]
scope = comb[1]
}
}
// Output of local.role_assignments_to_create:
// {
// "path-to-your-subscirption-1:Virtual_Machine_Contributor": {
// "role_definition_name": "Virtual Machine Contributor",
// "scope": "path-to-your-subscirption-1",
// },
// "path-to-your-subscirption-1:Compute_Gallery_Image_Reader": {
// "role_definition_name": "Compute Gallery Image Reader",
// "scope": "path-to-your-subscirption-1",
// },
// "path-to-your-subscirption-2:Virtual_Machine_Contributor": {
// "role_definition_name": "Virtual Machine Contributor",
// "scope": "path-to-your-subscirption-2",
// },
// "path-to-your-subscirption-2:Compute_Gallery_Image_Reader": {
// "role_definition_name": "Compute Gallery Image Reader",
// "scope": "path-to-your-subscirption-2",
// },
// }
}
Then with the role_assignments_to_create
variable, you can use for_each
to create resources:
resource "azurerm_role_assignment" "role_assignment" {
for_each = local.role_assignments_to_create
scope = each.value.scope
role_definition_name = each.value.role_definition_name
principal_id = xxxx
}