Search code examples
azureterraformazure-policyinfrastructure-as-code

How to assign existing multiple Azure policies to multiple resources with Terraform


I am using open source Terraform with AZURE and I am stuck at following task. Please advise if you have better solutions.

I have the IDs of Azure policies in a list

  variable "existing_policy_ids" {
     "policy-id1",
     "policy-id2",
     "policy-id3",
      ......
    }

I need to assign all these policies to resource group in Azure dynamically. The resource group has count meta argument like this:

resource "azurerm_resource_group" "my-rg" {
  count    = var.environment == "dev" ? 1 : 2
  name     = "my-rg-${count.index}"
  location = var.rg_location
}

Now the question is - How should the policy assignment look like, since there are multiple policies (10) while resource group can be 1 or 2 depending on environment. Means I can not use standard way of count or for_each?!

resource "azurerm_resource_group_policy_assignment" "assign-policy" {

  count        = length(azurerm_resource_group.my-rg.id)
  name         = "${azurerm_resource_group.my-rg[count.index].name}"
  policy_definition_id = var.existing_policy_id[count.index]  # ISSUE
  resource_group_id = azurerm_resource_group.my-rg[count.index].id   # ISSUE

}

Now the last 2 lines of Policy assignment block is where I am stuck. If I use count.index then the counter will only run once or max 2 times. While policies are more than 2.

Now how do I code that each resource_group that gets created, is assigned all the policies I have in the variable existing_policy_ids.

Thank you all in advance!


Solution

  • You have iterate over a cumulative list of both existing_policy_ids and the number of your azurerm_resource_group. In your case,you could use setproduct for that.

    locals {
      cummulative_list = setproduct(
            range(length(azurerm_resource_group.my-rg)), 
            var.existing_policy_ids)  
    }
    
    resource "azurerm_resource_group_policy_assignment" "assign-policy" {
      count     = length(local.cummulative_list)
      name      = azurerm_resource_group.my-rg[local.cummulative_list[count.index][0]].name
      policy_definition_id = local.cummulative_list[count.index][1] 
      resource_group_id = azurerm_resource_group.my-rg[local.cummulative_list[count.index][0]].id   
    }