Creating a record list from a terraform resource

Viewed 451

In Terraform, I'm trying to create a DNS SRV record from created DNS A records. I would like to populate the records with the names from the aws_route53_record.etcd names, but running into errors when referencing the resource names.

Is there an easy way to achieve this?

# This resource works without errors
resource "aws_route53_record" "etcd" {

  count = length(var.control_plane_private_ips)
  
  zone_id = data.aws_route53_zone.test.zone_id
  name    = "etcd-${count.index}.${data.aws_route53_zone.test.name}"
  type    = "A"
  ttl     = 60
  records = var.control_plane_private_ips

}

resource "aws_route53_record" "etcd_ssl_tcp" {

  zone_id = data.aws_route53_zone.test.zone_id
  name    = "_etcd-server-ssl._tcp.${data.aws_route53_zone.test.name}"
  type    = "SRV"
  ttl     = 60

  # code is producing an error here. Would like to add the names to the records
  for_each = [for n in aws_route53_record.etcd : { name = n.name }]
  records = [
    "0 10 2380 ${each.value.name}.${data.aws_route53_zone.test.name}"
  ]
 
}

When running a terraform plan, I get the following error.

Error: Invalid for_each argument

  on main.tf line 55, in resource "aws_route53_record" "etcd_ssl_tcp":
  55:   for_each = [for n in aws_route53_record.etcd : { name = n.name }]

The given "for_each" argument value is unsuitable: the "for_each" argument
must be a map, or set of strings, and you have provided a value of type tuple.
2 Answers

you use for_each and for in the same line. Both are describing loops and this makes it really hard to fallow. Try to split the line in 2 different lines and assign the for to a local variable. Splitting the for and for_each will help us check this.

I think the issue is [for n in aws_route53_record.etcd : { name = n.name }]

the starting bracket [for ... defines a list and the { name .. defines a map . So a list of maps. Perhaps to remove the { ?

Figured it out based on the feedback. Thanks for the help!

resource "aws_route53_record" "etcd_ssl_tcp" {

  zone_id = data.aws_route53_zone.kubic.zone_id
  name    = "_etcd-server-ssl._tcp.${data.aws_route53_zone.test.name}"
  type    = "SRV"
  ttl     = 60

  records = [
      for n in aws_route53_record.etcd :
      "0 10 2380 ${n.name}"
  ]

}
Related