地图列表中的地形循环

时间:2020-07-01 14:32:08

标签: terraform terraform-provider-azure

我有一个Terraform模块,该模块可生成地图输出列表:

object_ids = [
  {
    "object_id" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
    "upn" = "john@domain.com"
    "user" = "john"
  },
  {
    "object_id" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
    "upn" = "martin@domain.com"
    "user" = "martin"
  },
]

使用for_each,我可以循环使用一个值来构建此资源:

resource "azurerm_role_assignment" "subread" {
    for_each = toset(module.user.map_object_ids[*].object_id)
    scope                = data.azurerm_subscription.primary.id
    role_definition_name = "Reader"
    principal_id         = each.value
}

但是我不知道如何循环多个值。

对于另一个需要从输出中获得两个不同值的资源,我尝试了以下操作:

resource "azurerm_role_assignment" "contribrg" {
    scope                = [for map in module.user.map_object_ids[*]: "${data.azurerm_subscription.primary.id}/resourceGroups/${lookup(map,"user")}"]
    role_definition_name = "Contributor"
    principal_id         = [for map in module.user.map_object_ids[*]: lookup(map,"object_id")]
}

遇到以下错误:

Error: Incorrect attribute value type
module.user.map_object_ids is tuple with 2 elements
Inappropriate value for attribute "scope": string required.
Inappropriate value for attribute "principal_id": string required.

1 个答案:

答案 0 :(得分:1)

对资源for_each的基本要求是,您要使用的集合必须为每个实例创建一个元素,因此不可能基于多个值进行重复,但是幸运的是,我认为这实际上不是您要问的。

相反,似乎您想为module.user.map_object_ids的每个元素都拥有一个实例,因此我们需要处理的唯一另一个问题是for_each期望得到一个对象映射而不是对象列表,因此它可以将地图关键字用作每个实例的标识符。

我们可以使用for expression将对象列表转换为对象映射,尽管我们需要标识嵌套对象的属性之一,该属性将用作每个元素的唯一键。我将在这里使用user,因为它似乎是一个易于理解的,由配置选择的唯一标识符:

resource "azurerm_role_assignment" "contribrg" {
  for_each = { for obj in module.user.map_object_ids : obj.user => obj }

  scope                = "${data.azurerm_subscription.primary.id}/resourceGroups/${each.value.user}"
  role_definition_name = "Contributor"
  principal_id         = each.value.object_id
}

上面的for表达式会将您的对象列表投影到对象映射中,如下所示:

{
  "john" = {
    "object_id" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
    "upn" = "john@domain.com"
    "user" = "john"
  }
  "martin" = {
    "object_id" = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
    "upn" = "martin@domain.com"
    "user" = "martin"
  }
}

然后在资源参数表达式each.key中将引用用户名(因为它们现在是键),而each.value将引用对象,因此我们可以使用each.value.object_id来命名获取相应的对象标识符。

由此,Terraform将计划创建具有以下地址的资源实例:

  • azurerm_role_assignment.contribrg["john"]
  • azurerm_role_assignment.contribrg["martin"]

一个旁注:我发现您的输出不仅返回ID时还被命名为object_ids,这有点令人困惑。将其命名为objects可能更清楚。