azurerm_dns_txt_record 在模块记录块中使用的 Terraform 重构

Terraform refactoring for azurerm_dns_txt_record use in a module record block

我在 terraform 模块中有以下代码:

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]
}

这似乎不是一种添加记录块的非常干净的方法,但我找不到更好的方法。

我试过用这种方式重构它:

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]
}

但不幸的是,这会在我们的 DNS 中产生一个 MX 记录,我们应该在其中插入 7 个项目。似乎每一项都插入到前一项之上。

如您所见,资源中的每个记录块都需要分开:MX record resource

有谁能想出更好的方式来构造这个地形?

您的动态块应该是:

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

    content {
      value = record.value
    }
  }

没有

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

    content {
      value = i.value
    }
  }