Terraform 多个 AWS route53 MX 记录

Terraform multiple AWS route53 MX records

我在 tf 中有 locals 可以将 MX 记录推送到 cloudflare,它的工作原理正是我想要的。我想对 Route53 使用相同的 locals,但对于 route53,records 应该合并为一个。我如何使用 blow locals 使用 terraform 推送到 Route53。

locals {
    MXRecordSets = [
         {
            Name =  "example.com.",
            Type =  "MX",
            TTL =  3600,
            MXRecords =  [
                {
                    "Value" =  "1 aspmx.l.google.com"
                },
                {
                     "Value" =  "5 alt1.aspmx.l.google.com"
                 }
            ]
        }
    ]
}
locals {
    FlatMXRecordSets = merge([
    for idx, MXRecordSet in local.MXRecordSets:
      {
        for MXRecord in MXRecordSet.MXRecords:
            "${idx}-${MXRecord.Value}" => {
              MXRecordSet = MXRecordSet
              MXRecord =  MXRecord["Value"]
          }
      }
    ]...)
}

最后我使用下面的 aws route53 模块将更改推送到 AWS,但它不起作用:

resource "aws_route53_record" "mx_records" {
  for_each =local.FlatMXRecordSets
  zone_id  = aws_route53_zone.carfeine_com.id
  name     = each.value["MXRecordSet"].Name
  type     = each.value["MXRecordSet"].Type
  records  = [ each.value["MXRecord"] ]
  ttl      = 1
}

错误是 [Tried to create resource record set [name='example.com.', type='MX'] but it already exists] 因为我正在使用 for_each 而我不应该使用它。还有其他方法吗?

你的MXRecordSets已经是平的了,所以不需要压平。但它也是一个地图列表,这可能会导致更多问题,因为列表取决于项目的顺序。因此,如果可能的话,最好只使用地图中的地图:

locals {
    MXRecordSets = {
       "mail.mwotest.xyz." = {
            Type =  "MX",
            TTL =  3600,
            MXRecords =  [
                {
                    "Value" =  "1 aspmx.l.google.com"
                },
                {
                     "Value" =  "5 alt1.aspmx.l.google.com"
                 }
            ]
        }
    }            
}

然后

resource "aws_route53_record" "mx_records" {
  for_each = local.MXRecordSets
  zone_id  = aws_route53_zone.carfeine_com.id
  name     = each.key
  type     = each.value.Type
  records  = [ for key,record in each.value["MXRecords"]: record["Value"] ]
  ttl      = 1
}

在上面,

 [ for key,record in each.value["MXRecords"]: record["Value"] ]

将为 MX 生成正确的 records 作为:

records = ["1 aspmx.l.google.com", "5 alt1.aspmx.l.google.com"]