Possible to use two different for_each loops in same resource block

Is it possible to use this

resource "azurerm_network_security_group" "this" {

  for_each = {
        for sg in local.nsgs:
          sg.nsg_name => sg...
  }
  name                = each.value.nsg_name
  location            = var.location
  resource_group_name = var.resource_group_name

  dynamic "security_rule" {
    for_each = {
          for sg in local.nsgs:
            "${sg.rule}.${sg.name}" => sg
    }
    content {
      name                       = each.value.name
      priority                   = each.value.priority
      direction                  = each.value.direction
      access                     = each.value.access
      protocol                   = each.value.protocol
      source_port_range          = each.value.source_port_range
      destination_port_range     = each.value.destination_port_range
      source_address_prefix      = each.value.source_address_prefix
      destination_address_prefix = each.value.destination_address_prefix
   }
  }
} 

I have two different flatten blocks that define structure for keys corresponding to names of network security groups and another one that defines all rules of the security groups.

The one above gives error because the second for_each never comes in context. The error:

  59:       destination_address_prefix = each.value.destination_address_prefix
    |----------------
    | each.value is tuple with 2 elements

shows that the first for_each loop still is in context and the second one never becomes active.

Hi @faizan82,

The dynamic blocks feature works a little differently than for_each on resources. The iterator in that context is the block name by default, not “each”. Try the configuration using security_rule rather than each.