A single DNS name with multiple A records - what is the syntax

Dear Colleages,

Which syntax should I use for this configuration: I have N identical EC2 instances named “www” and would like to create a single DNS RR with the IPs of all those N instances for load balancing.

I’ve tried the variants below and neither of them does what I need. Can you please give me a hand?

resource "aws_route53_record" "www" {
  count   = 1
  zone_id = var.dns_zone
  name    = "www"
  type    = "A"
  ttl     = "300"
  records = ["${element(aws_instance.www.*.public_ip, count.index)}"]
} // creates record with only one IP

resource "aws_route53_record" "www" {
  count   = 1
  zone_id = var.dns_zone
  name    = "www"
  type    = "A"
  ttl     = "300"
  records = [aws_instance.www.*.public_ip]
} // gives error

I probably need some kind of loop to iterate over the aws_instance.www.*.public_ip list.

When I use the configuration records = ["10.6.6.6", "10.7.7.7"] I see two IP addresses for the “www” record as desired. So a list is OK there. I just need to convert the result of aws_instance.www.*.public_ip into a list. Please help?

It’s already a list - just use it as is, without putting another set of square brackets around it.

@maxb Oh, thanks a lot! I’ve outsmarted myself. Of course
records = aws_instance.www.*.public_ip
works as expected.

@maxb Another related question if you don’t mind. Do you think it’s possible to avoid a Terraform error when the aws_instance.www.*.public_ip list becomes empty? When I scale the number of “www” instances down to 0, I would like the DNS record to either be deleted altogether (or not created from the start) or the IPs to be replaced with some default value like 127.0.0.1. How can I do that?

The only way Terraform has to make a resource block conditional, is to set count to 0 or 1.

So, you could do:

  count = length(aws_instance.www) > 0 ? 1 : 0

Seems to work, thank you @maxb ! A smart way of doing it.

I also had to change the output value from
value = aws_route53_record.www.fqdn
to value = aws_route53_record.www.*.fqdn
so it’s changed from string to list but it’s a minor inconvenience.

value = one(aws_route53_record.www.*.fqdn) is even better,when we have either 0 or 1 record.