Home > database >  multiple roles in a resource block for azurerm_role_assignment
multiple roles in a resource block for azurerm_role_assignment

Time:10-15

I am new to Terraform and learning. I have to provide two roles in a resource block(builtin and custom), is this supported in 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:

 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.

I am already using for_each to pull in a list of principal_ids within the resource block, so I am wondering if there is a way to set this in a loop, so both the roles are applicable to the concerned principal_id.

I am unable to see any good example where there are multiple roles in a resource block.. Any suggestions?

CodePudding user response:

role_definition_name should be string,not a list. You can try the following:

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
}

The exact form depends on how local.principal_ids defined, but sadly you are not providing such information in the question.

CodePudding user response:

role_definition_name cant be a list, so you have to update your code:

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
}
  • Related