Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to consolidate duplicate blocks for Azure Role Assignments using Terraform?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading