Terraform 构建变更集时出错:循环遍历多个 Route53 记录时 InvalidChangeBatch

Terraform error building changeset: InvalidChangeBatch when looping through multiple Route53 Records

我有使用 for_each 命令创建的 Route 53 记录。我的一条记录与其条目相关联的值超过 1 个。这是记录的声明方式:

variables.tf

variable "mx" {
  type = map(object({
    ttl     = string
    records = set(string)
  }))
}

variables.tf变量

mx = {
  "mywebsite.org." = {
    ttl = "3600"
    records = [
      "home.mywebsite.org.",
      "faq.mywebsite.org."
    ]
  }
  "myotherwebsite.org." = {
    ttl = "3600"
    records = [
      "home.myotherwebsite.org."
    ]
  }

mx.tf

locals {
  mx_records = flatten([
    for mx_key, mx in var.mx : [
      for record in mx.records : {
        mx_key = mx_key
        record = record
        ttl    = mx.ttl
    }]
  ])
}

resource "aws_route53_record" "mx_records" {
  for_each = { for idx, mx in local.mx_records : idx => mx }
  zone_id  = aws_route53_zone.zone.zone_id
  name     = each.value.mx_key
  type     = "MX"
  ttl      = each.value.ttl

  records = [
    each.value.record
  ]
}

执行时一切正常,直到 Terraform 意识到我的记录有额外的价值。然后它会生成以下错误:

Error building changeset: InvalidChangeBatch: [Tried to create resource record set 

[name='mywebsite.org.', type='MX'] but it already exists]

我的问题是,有没有办法让 Terraform 不为此值创建第二个条目?对于 Route53,所有记录名称都必须是唯一的。 Terraform 是否有办法简单地将此值添加到此记录,因为它是在执行的初始 运行 中创建的?随着这变得具有挑战性,我们将不胜感激。

更新 删除展平并更新为 'records = [each.value.records]' 后,这是错误:

Error: Unsupported attribute



 on mx.tf line 20, in resource "aws_route53_record" "mx_records":
  20:     each.value.record
    |----------------
    | each.value is tuple with 2 elements

This value does not have any attributes.


Error: Unsupported attribute

  on mx.tf line 20, in resource "aws_route53_record" "mx_records":
  20:     each.value.record
    |----------------
    | each.value is tuple with 1 element

This value does not have any attributes.

我认为您可以直接使用 mx ,而不是将其转换为 mx_records

您可以尝试以下方法:

resource "aws_route53_record" "mx_records" {

  for_each = var.mx
  
  zone_id  = aws_route53_zone.zone.zone_id
  name     = each.key
  type     = "MX"
  ttl      = each.value.ttl

  records = each.value.records

}

上面的for_each应该只执行两次。第一个用于 mywebsite.org.,第二个用于 myotherwebsite.org.