azurerm_role_assignment 资源块中的多个角色

multiple roles in a resource block for azurerm_role_assignment

我是 Terraform 的新手,正在学习。 我必须在资源块中提供两个角色(内置和自定义),这在 terraform 中受支持吗?

variable "role_definition_id" {
  type = list(string)
  description = "Role definition id"
  default = ["READER", "Custom_role"]
}

resource "azurerm_role_assignment" "example" {
  for_each = toset(local.principal_ids)
  scope = data.azurerm_subscription.primary.id
  role_definition_name = var.role_definition_id
  principal_id = each.key
}

错误:

 Error: Incorrect attribute value type
│
│   on namespace/main.tf line 109, in resource "azurerm_role_assignment" "example":
│  109:   role_definition_name = var.role_definition_id
│     ├────────────────
│     │ var.role_definition_id is a list of dynamic, known only after apply
│
│ Inappropriate value for attribute "role_definition_name": string required.

我已经在使用 for_each 在资源块中拉入 principal_ids 的列表,所以我想知道是否有办法在循环中设置它,所以这两个角色适用于有关 principal_id.

我看不到资源块中有多个角色的任何好例子.. 有什么建议吗?

role_definition_name 应该是 string,不是列表。您可以尝试以下方法:

resource "azurerm_role_assignment" "example" {
  for_each = {for idx, value in toset(local.principal_ids): idx=>value}
  scope = data.azurerm_subscription.primary.id
  role_definition_name = element(var.role_definition_id, each.key)
  principal_id = each.value.id
}

确切的形式取决于 local.principal_ids 的定义方式,但遗憾的是您没有在问题中提供此类信息。

role_definition_name 不能成为一个列表,所以你必须更新你的代码:

resource "azurerm_role_assignment" "example" {
  for_each = toset(local.principal_ids)
  scope = data.azurerm_subscription.primary.id
  role_definition_name = "READER"
  principal_id = each.key
}

resource "azurerm_role_assignment" "example" {
  for_each = toset(local.principal_ids)
  scope = data.azurerm_subscription.primary.id
  role_definition_name = "Custom_role"
  principal_id = each.key
}