简体   繁体   中英

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

I have Route 53 records that I am creating with the for_each command. One of my records has more than 1 values associated with its entry. This is how the records are declared:

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

At execution everything works well up until Terraform realizes I have an additional value for my record. It then generates the error below:

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

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

My question is, is there a way to get Terraform to not create a second entry for this value? For Route53 all the record names have to be unique. Is there a way for Terraform to simply add on this value to this record since it was created in the initial run of execution? Any help would be appreciated as this becoming challenging.

UPDATE After removing flatten and updating to 'records = [each.value.records]', this is the error:

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.

I think you could just use your mx directly , instead of transforming it into mx_records .

You could try the following:

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

}

The above for_each should execute twice only. First for mywebsite.org. and the second for myotherwebsite.org. .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM