用于记录的 terraform cloudflare 循环

terraform cloudflare loop for records

我有一个 terraform cloudflare push 的设置,配置如下:

locals {
    ResourceRecordSets= [
        {
            Name =  "example.com.",
            Type =  "A",
            TTL =  60,
            ResourceRecords =  [
                {
                    Value =  "1.2.3.4"
                }
            ]
        }

使用此 locals 值,我将 DNS 记录推送为:

resource "cloudflare_record" "com_records" {
  count = length(local.ResourceRecordSets)

  zone_id = cloudflare_zone.site.id
  name    = local.ResourceRecordSets[count.index].Name
  value   = local.ResourceRecordSets[count.index].ResourceRecords.value
  type    = local.ResourceRecordSets[count.index].Type
  proxied = false
  ttl     = 1
}

我唯一纠结的是 value 部分。有时它可以是 MX 条记录,在 ResourceRecords 下有多个值。我应该使用哪种类型的循环?

您必须展平您的 ResourceRecordSets,例如:

  FlatResourceRecordSets = merge([
    for idx, ResourceRecordSet in local.ResourceRecordSets:
      {
        for ResourceRecord in ResourceRecordSet.ResourceRecords:
            "${idx}-${ResourceRecord.Value}" => {
              ResourceRecordSet = ResourceRecordSet
              ResourceRecord =  ResourceRecord["Value"]
          }
      }
    ]...) # please do NOT remove the dots   

然后

resource "cloudflare_record" "com_records" {
  for_each = local.FlatResourceRecordSets

  zone_id = cloudflare_zone.site.id
  name    = each.value["ResourceRecordSet"].Name
  value   = each.value["ResourceRecord"]
  type    = each.value["ResourceRecordSet"].Type
  proxied = false
  ttl     = 1
}