I'm currently working on managing role assignments in Terraform for Azure Storage Access, and I'm looking to streamline my code. Below is the snippet I'm working with,
locals {
sa_we = "0c975d82-85a2-4b3a-bb23-9be5c681b66f"
sa_gl = "9ee248b1-26f6-4d72-a3ac-7b77cf6c17f2"
}
resource "azurerm_role_assignment" "storage_account_access" {
scope = azurerm_storage_account.jd-messenger.id
role_definition_name = "Storage Blob Data Reader"
principal_id = local.sa_we
}
resource "azurerm_role_assignment" "storage_account_access" {
scope = azurerm_storage_account.jd-messenger.id
role_definition_name = "Storage Blob Data Reader"
principal_id = local.sa_gl
}
I'm wondering if there's a more efficient way to handle these role assignments. Specifically, I'm interested in consolidating these duplicate resource blocks into a single block, eliminating redundancy while still specifying different principal_id values.
Any insights or suggestions on how to achieve this would be greatly appreciated!
I would suggest recreating the local variable as a map:
locals {
storage_accounts = {
sa_we = "0c975d82-85a2-4b3a-bb23-9be5c681b66f"
sa_gl = "9ee248b1-26f6-4d72-a3ac-7b77cf6c17f2"
}
}
Then, using the for_each
meta-argument you could use the resource block only once:
resource "azurerm_role_assignment" "storage_account_access" {
for_each = local.storage_accounts
scope = azurerm_storage_account.jd-messenger.id
role_definition_name = "Storage Blob Data Reader for ${each.key}"
principal_id = each.value
}