首页 > 解决方案 > 每个循环或 for 循环的 Terraform 不起作用

问题描述

我正在尝试为多个服务主体的 azure 容器注册表设置角色

variable "custom_role_list" {

  type        = list(object ({ service_principal_id = string, role = string }) )

} 

当我尝试从资源模块设置它时,我不确定这是正确的方法吗?

resource "azurerm_role_assignment" "ad_sp_role_assignment" {

  scope                = azurerm_container_registry.acr.id
  for_each = var.custom_role_list
  role_definition_name           = each.value.role
  principal_id = each.value.service_principal_id

}

本质上,我正在尝试将 azure 容器注册表设置为与具有特定访问角色的多个服务主体一起使用。

以下是 var 定义。

custom_role_list = [
    {
        service_principal_id = aserviceprincipal.id
        role = "Contributor"
    },

    {
        service_principal_id = bserviceprincipal.id
        role = "Contributor"
    }


]

当我执行它时,我收到以下错误。

Error: Invalid for_each argument

  on ../modules/az-acr/main.tf line 46, in resource "azurerm_role_assignment" "ad_sp_role_assignment":
  46:   for_each = var.custom_role_list

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 list
of object.

请如果有人可以指导将非常有帮助。谢谢!

标签: terraformterraform-provider-azureterraform0.12+

解决方案


正如错误所暗示的,for_each仅在与资源一起使用时才支持地图和集合。您正在尝试使用对象列表。

相反,也许您的变量可以是简单的 type map,其中每个服务原则是一个键,其对应的角色是值。例如:

variable "custom_role_list" {
  type        = map
}

变量定义:

custom_role_map = {
  aserviceprincipal.id = "Contributor"
  bserviceprincipal.id = "Contributor"
}

最后使用for_each

resource "azurerm_role_assignment" "ad_sp_role_assignment" {
  for_each = var.custom_role_map

  scope                    = azurerm_container_registry.acr.id
  role_definition_name     = each.value
  principal_id             = each.key
}

您可能会发现这篇博文可以帮助您在 Terraform 中使用循环和条件。


推荐阅读