0

我正在尝试为多个服务主体的 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.

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

4

2 回答 2

2

正如错误所暗示的,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 中使用循环和条件。

于 2020-03-30T23:34:38.300 回答
0

for_each通过将代码调整为以下内容,您可以在对象列表中使用循环:

variable "custom_role_list" {
  type = list(object({
    service_principal_id = string
    role  = string 
  }))
  default = [
    {
        service_principal_id= "27d653c-aB53-4ce1-920",
        role  = "Contributor"
    },
     {
        service_principal_id= "57d634c-aB53-4ce1-397",
        role  = "Contributor"
    }
  ]
}
    
resource "azurerm_role_assignment" "ad_sp_role_assignment" {

for_each = {for sp in var.custom_role_list: sp.service_principal_id => sp}
    
scope                    = azurerm_container_registry.acr.id
role_definition_name     = each.value.service_principal_id 
principal_id             = each.value.role 
}
于 2020-10-21T11:14:40.903 回答