Iterating Two Maps Inside A Resource using for_each

284 Views Asked by At

I'm Trying to create azure SRV record based on some condition, for this multiple target is needed for a single SRV record. If I iterate inside dynamic each.key and each.value is referring the key value outside the dynamic block. is there a way to iterate this record block for required number of time. Also the count is not supported in record block. Could there be any other ways to achieve this without loop also fine.

NOTE: this is a pseudo code for reference.

resource "azurerm_dns_srv_record" "srv_dns_record" {
  for_each            = { for key, value in var.clusters : key => value if some condition }
  name                = name
  zone_name           = azurerm_dns_zone.cluster_dns_zone[each.key].name
  resource_group_name = azurerm_resource_group.main.name
  ttl                 = 60

  dynamic "record" {
    for_each = var.targets
    content {
      priority = 1
      weight   = 5
      port     = 443
      target   = each.key
    }
  }

Thanks!

2

There are 2 best solutions below

0
Marcin On BEST ANSWER

If you want to iterate over var.targets in side a dynamic block, it should be:

target   = record.key
1
Chris Doyle On

from the docs

The iterator argument (optional) sets the name of a temporary variable that represents the current element of the complex value. If omitted, the name of the variable defaults to the label of the dynamic block ("setting" in the example above).

so to refer to the value of the iterated field in the dynamic block you should use the label of the block not the each word

resource "azurerm_dns_srv_record" "srv_dns_record" {
  for_each            = { for key, value in var.clusters : key => value if some condition }
  name                = name
  zone_name           = azurerm_dns_zone.cluster_dns_zone[each.key].name
  resource_group_name = azurerm_resource_group.main.name
  ttl                 = 60

  dynamic "record" {
    for_each = var.targets
    content {
      priority = 1
      weight   = 5
      port     = 443
      target   = record.key
    }
  }