我正在尝试为多个服务主体的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.
如果有人可以指导,请帮忙。谢谢!
答案 0 :(得分:2)
错误提示,for_each
仅在与资源一起使用时才支持映射和集合。您正在尝试使用对象列表。
相反,也许您的变量可以简单地是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
}
您可能会发现this blog post可以帮助您在Terraform中使用循环和条件。
答案 1 :(得分: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
}