azureterraformterraform-provider-azureterraform-template-filehashicorp

How to create multiple private DNS zones and then on each zone create multiple private DNS virtual link using for each loop in terraform azure


create multiple private DNS zones and then on each zone create multiple private DNS virtual link using for each loop in terraform azure. and I am unable to create multiple virtual network links on each zone.

variable "privateDnsZones" {
  type = map(object({
    virtualNetworksID = list(string)
  }))
  default = {
    "privatelink.monitor.azure.com" = {
      virtualNetworksID = [
        "",
        ""
      ]
    },
    "privatelink.oms.opinsights.azure.com" = {
      virtualNetworksID = [
        "",
        ""
      ]
    }
  }
}

resource "azurerm_private_dns_zone" "privateDnsZone" {
  for_each            = var.privateDnsZones
  name                = each.key
  resource_group_name = data.azurerm_resource_group.existing_RG.name
  tags                = var.resource_tags
  
}

resource "azurerm_private_dns_zone_virtual_network_link" "privateDnsZone_link" {
    for_each =
  name                  = 
  resource_group_name   = 
  private_dns_zone_name = 
  virtual_network_id    = 
}

Solution

  • Without having tested it, it should work roughly like this:

    locals {
      # flatten ensures that this local value is a flat list of objects, rather
      # than a list of lists of objects.
      zones_vnets = flatten([
        for zone_key, zone in var.privateDnsZones: [
          for vnetId in zone.virtualNetworksID : {
            zoneId = azurerm_private_dns_zone.privateDnsZone[zone_key].id
            vnetId = vnetId
          }
        ]
      ])
    }
    
    resource "azurerm_private_dns_zone_virtual_network_link" "privateDnsZone_link" {
      for_each = {
        for zone in local.zones_vnets: "${zone.zoneId}.${zone.vnetId}" => zoneLink
      }
      name                  = each.key
      resource_group_name   = "foobar-rg"
      private_dns_zone_name = each.value.zoneId
      virtual_network_id    = each.value.vnetId
    }