Search code examples
terraformazure-rmterraform-modules

Terraform refactoring for azurerm_dns_txt_record use in a module record block


I've got the following code in a terraform module:

locals {
  txt_records = flatten(
    [
      for i in var.DnsZones :
      {
          zone_name           = i.ZoneName
          resource_group_name = i.ResourceGroup
          name                = "@"
          ttl                 = i.Ttl
          records             = i.TxtRecords
      }
    ]
  )
}

resource "azurerm_dns_zone" "zone" {
  count               = length(var.DnsZones)
  name                = var.DnsZones[count.index].ZoneName
  resource_group_name = var.DnsZones[count.index].ResourceGroup
}


resource "azurerm_dns_txt_record" "record-txt" {
  count               = length(local.txt_records)
  resource_group_name = local.txt_records[count.index].resource_group_name
  zone_name           = local.txt_records[count.index].zone_name
  ttl                 = local.txt_records[count.index].ttl
  name                = local.txt_records[count.index].name

  record {
    value = local.txt_records[count.index].records[0]
  }
  record {
    value = local.txt_records[count.index].records[1]
  }
  record {
    value = local.txt_records[count.index].records[2]
  }
  record {
    value = local.txt_records[count.index].records[3]
  }
  record {
    value = local.txt_records[count.index].records[4]
  }
  record {
    value = local.txt_records[count.index].records[5]
  }
  record {
    value = local.txt_records[count.index].records[6]
  }

  depends_on = [azurerm_dns_zone.zone]
}

It doesn't seem like a very clean way of adding record blocks, but i can't find a better way of doing it.

I've tried refactoring it in this way:

resource "azurerm_dns_txt_record" "record-txt" {
  count               = length(local.txt_records)
  resource_group_name = local.txt_records[count.index].resource_group_name
  zone_name           = local.txt_records[count.index].zone_name
  ttl                 = local.txt_records[count.index].ttl
  name                = local.txt_records[count.index].name


  dynamic "record" {
    for_each = local.txt_records[count.index].records
    iterator = i

    content {
      value = i.value
    }
  }

  depends_on = [azurerm_dns_zone.zone]
}

but unfortunately, this results in a single MX record in our DNS where we should have 7 items inserted. It seems that each item gets inserted on top of the previous one.

As you can see each of the record blocks needs to be separated in the resource: MX record resource

Can anyone think of a better way of structuring this terraform?


Solution

  • Your dynamic block should be:

      dynamic "record" {
        for_each = local.txt_records[count.index].records
    
        content {
          value = record.value
        }
      }
    

    not

      dynamic "record" {
        for_each = local.txt_records[count.index].records
    
        content {
          value = i.value
        }
      }