Search code examples
amazon-web-servicesterraformload-balancingamazon-route53amazon-elb

How in Terraform to get a LB name created in another module (for a DNS records' creation)


I'm creating a DNS record AWS using Terraform (v. 12.10) and want to get the name of the ALB, which already was created (in another module).

I've read the documentation but didn't found any solution. Is there any way to do it?

resource "aws_route53_record" "dns" {
  provider        = <AWS>
  zone_id         = <ZONE_ID>
  name            = <NAME>
  ttl             = 30
  type            = "CNAME"
  records         = <LB_created_previously>
}

Solution

  • You basically have two options here.

    Option 1 - if your resource creation (in your case the DNS records) and the ALB created by the module are in the same place (same terraform.tfstate file) - this is more or less covered by samtoddler answer above or with you pseudo-code it will look something like this:

    resource "aws_route53_record" "dns" {
      provider        = <AWS>
      zone_id         = <ZONE_ID>
      name            = <NAME>
      ttl             = 30
      type            = "CNAME"
      records         = [module.<LB__module_definiton_name>.elb_dns_name]
    }
    

    where in your ELB module you would need something like:

    output "elb_dns_name" {
    value = aws_elb.<LB_created_previously>.dns_name
    }
    

    In option Two, you must have the same output defined in the module itself. However, if your DNS resource code is in a different folder / terraform state, you'll need to resort to a terraform remote state:

    data "terraform_remote_state" "elb" {
      backend = "mybackendtype"
      config = {
        ...
      }
    }
    

    And then you code will look like this:

    resource "aws_route53_record" "dns" {
      provider        = <AWS>
      zone_id         = <ZONE_ID>
      name            = <NAME>
      ttl             = 30
      type            = "CNAME"
      records         = [data.terraform_remote_state.elb.outputs.elb_dns_name]
    }
    

    Btw, when you have an ELB it's better to use an Alias instead of a CNAME record, which based on the terraform documentation for the dns records resource and your pseudo-code will be:

    resource "aws_route53_record" "dns" {
      zone_id         = <ZONE_ID>
      name            = <NAME>
      type    = "A"
    
      alias {
        name                   = module.<LB__module_definiton_name>.elb_dns_name
        zone_id                = module.<LB__module_definiton_name>.elb_zone_id
        evaluate_target_health = true
      }
    }