Home > Blockchain >  Create resource for each value in a map
Create resource for each value in a map

Time:07-21

I am trying to create a resource for each value in a map.

For example, I need to create a azuread_application_password resource. I would like a new secret per user of the application, so I have created a map that container the person using the application, and which parts of the application they can have access to:

variable "users" {
  type        = map(list(string))
}

users = {"user_1" : ["area_1", "area_2"], "user_2" : ["area_3", "area_4"]}

The value in the map also corresponds to the name of the application created via a azuread_application

resource "azuread_application_password" "client_secret" {
  for_each              = var.users
  display_name          = "Secret-${each.key}"
  application_object_id = azuread_application.auth[each.value].object_id
}

I would like to end up with an azuread_application_password created for each value in the map, and the display name to be the key.

The above block does not work because each.value is a list(string)

CodePudding user response:

You have to flatten your map:

locals {
  users_flat = merge([
            for user, areas in var.users: {
              for area in areas:
                "${user}-${area}" => {
                    "area" = area
                    "user" = user
                }
            }
        ]...)
}

then

resource "azuread_application_password" "client_secret" {
  for_each              = local.users_flat
  display_name          = "Secret-${each.value.user}"
  application_object_id = azuread_application.auth[each.value.area].object_id
}
  • Related