terraform - 每个循环或 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.
请如果有人可以指导将非常有帮助。谢谢!
解决方案
正如错误所暗示的,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 中使用循环和条件。
推荐阅读
- javascript - 将回调代码改进为异步等待猫鼬
- javascript - 如何使用带有 0x 的 javascript 将 Double 转换为十六进制
- javascript - WebHID API:重新连接设备
- java - Android Java OutputStream将整个文件缓冲成流
- flutter - 颤动:不导航到另一个页面
- windows - 在 Perl 脚本中无法将目录添加到存档
- html - CSS自动隐藏/显示每2秒
- r - 我们如何拆分字符串并提取圆括号之间的文本
- javascript - 如何制作不同屏幕尺寸的响应式同位素画廊插件?
- r - 如何在输出中使用反应式表达式的结果