【问题标题】:Terraform error building changeset: InvalidChangeBatch when looping through multiple Route53 RecordsTerraform 错误构建变更集:循环通过多个 Route53 记录时的 InvalidChangeBatch
【发布时间】:2020-08-03 22:53:17
【问题描述】:

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

variables.tf

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

variables.tfvars

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 有没有办法简单地将这个值添加到这个记录中,因为它是在执行的初始运行中创建的?任何帮助将不胜感激,因为这变得具有挑战性。

更新 删除 flatten 并更新为 '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.

【问题讨论】:

  • 你有记录作为一个列表,为什么扁平化?将记录保存为列表并执行records = each.value.records。正如您所指出的,您是在告诉 terraform 在此处创建副本。
  • 据我了解,我需要展平以便分别处理列表中的每个索引。如果我删除 flatten 并更新为“records = each.value.records”,Terraform 会将其视为元组。然后它会出错(在应用之前)。我将编辑并添加错误。

标签: amazon-web-services foreach terraform amazon-route53


【解决方案1】:

我认为您可以直接使用您的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.。

【讨论】:

  • 谢谢。如果我的记忆是准确的,我以为我已经尝试过上面的这个方法,但由于某种原因它让我很困惑。也许这是我忽略的一个小细节。再次感谢您。
猜你喜欢
  • 2019-08-04
  • 1970-01-01
  • 2021-10-21
  • 2018-08-20
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 2020-02-08
相关资源
最近更新 更多