'Issue to get all hosted zone id of AWS ELB through Terraform

I have created two AWS NLBs in the same region through terraform. Now I have to make DNS records in Route53 with type alias. But there are an error.

Error: [ERR]: Error building changeset: InvalidChangeBatch: [Tried to create an alias that targets 11111111111111111111111-xxxxxxxxxxxx.elb.eu-west-2.amazonaws.com., type A in zone ZHURV0000000, but the alias target name does not lie within the target zone] status code: 400, request id: 2xxxxxxxxxxxxxxxxx

It was working fine, when I had only single NLB. because, we need ELB zone id to make DNS entry with alias type. and both NLB has different zone ID. but terraform is providing only single zone id through below code.

data "aws_elb_hosted_zone_id" "main" {}

Im taking reference from below link: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/elb_hosted_zone_id

The ultimate problem is: How to get the 2nd, 3rd .. zone id of ELB in the same region ??



Solution 1:[1]

There is no such thing as second and third zone id for elastic load balancing. There is one per region for everyone, in fact you can get the IDs from here: https://docs.aws.amazon.com/general/latest/gr/elb.html.

You can reuse the same data block for multiple records. What will change is the domain name which is unique for each load balancer:

resource "aws_route53_record" "www" {
  ...
  type    = "A"

  alias {
    name    = aws_lb.my_network_load_balancer.dns_name # This changes based on load balancer
    zone_id = data.aws_elb_hosted_zone_id.main # The remains the same for each record 
  }
}

Update:

data "aws_elb_hosted_zone_id" "main" {} does not work with network load balancers. We can get the canoical hosted zone id by referencing an attribute of aws_elb resource: aws_lb.my_network_load_balancer.zone_id.

Solution 2:[2]

Finally I got below solution for NLB DNS entry: Here, I'm fetching zone id from the NLB name.

Note: "aws_elb_hosted_zone_id" will provide you zone id of the ALB, not NLB

  resource "aws_route53_zone" "this" {
  name = lower("${var.base_domain_name}")
}

#get DNS zone
data "aws_route53_zone" "this" {
  name = lower("${var.base_domain_name}")
  depends_on = [
  aws_route53_zone.this
]
}

data "aws_lb" "my_nlb" {
  name = "my-nlb"
}

resource "aws_route53_record" "nlb_dns" {
  zone_id = data.aws_route53_zone.this.zone_id
  name    = "my-nlb-dns"
  type    = "A"
  alias {
    name                   = "my_nlb-0000000.us-east-1.elb.amazonaws.com"
    zone_id                = data.aws_lb.my_nlb.zone_id  # this is the fix
    evaluate_target_health = true
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 santosh verma