Search code examples
amazon-web-servicesterraformterraform-provider-awsroute53

Add an alias record to existing hosted zone


I am pretty new to terraform but I have a decent grip on AWS. I have a main.tf that I have used to provision 2 EC2s in different AZs, attach existing Security Groups and create an ALB. When I add code for route 53 instead of adding an alias record pointing to the ALB it creates an entirely new HZ. Is there any way to just create an alias in the existing HZ? Here is the relevant part of main.tf:

resource "aws_route53_zone" "primary" {
  name = "<mydomain>"
}

resource "aws_route53_record" "alias_route53_record" {
  zone_id = aws_route53_zone.primary.zone_id
  name    = "<mydomain>"
  type    = "A"

  alias {
    name                  = aws_lb.load_balancer.dns_name
    zone_id               = aws_lb.load_balancer.zone_id
    evaluate_target_health = true
  }
}

Solution

  • When a resource already exists there are two options:

    1. Import it into terraform if not already there
    2. If it is already in terraform, use a data source to fetch the information

    In this case I will assume you want to use the data source, so the code would look something like the following:

    data "aws_route53_zone" "primary" {
      name = "<mydomain>."
    }
    
    resource "aws_route53_record" "alias_route53_record" {
      zone_id = data.aws_route53_zone.primary.zone_id
      name = "<record name>" # you don't need the entire domain here, only the record name
      type = "A"
    
      alias {
        name                   = aws_lb.load_balancer.dns_name
        zone_id                = aws_lb.load_balancer.zone_id
        evaluate_target_health = true
      }
    }
    

    It is also worth noting that you might need to use provider aliases if you want the code to work in two different AZs.