When using Route53 for DNS, you have the option of using a special AWS only type of record for the Apex or Root record of the domain (zone). Taking an example domain.com, you typically would have a website which has an A record called www.domain.com. But what if you want to have the apex of the domain also be resolvable? i.e. so a user can go to “domain.com” and still get to the website.
In this case you need to create an Apex (Root) record, what makes this different is that an Apex (Root) A record can’t be a CNAME, it must be an A record that points at an IP address. Sure that might be fine if you are hosting something at a particular IP address, but normally you’d be using something like CNAME for www.domain.com which points to some hosting server(s) which have an A record, to make administration easy and negate the need to update many records if the IP address ever needed to change. Of course if you are then using something like an Application Load Balancer or other dynamic cloud service, you may not be able to reliably find an IP address(es) to use in this Apex (Root) record and even if you did, the cloud provider could change them at a whim!
To get around this AWS provides an “alias” type of record that allows this Apex (Root) A record to alias to something else, the example below sets up an A record forĀ www.domain.com which points to an Elastic IP Address, but then also creates as Apex (Root) record that points to this A record all within the zone www.domain.com, which is a pre-existing Route 53 zone created outside of the Terraform script, hence they we are adding it as a variable and only adding records within the pre-created zone.
// DNS Record ---------
# We already have a Route53 Zone created, so we just want to add an A record to that zone for "www" and the "apex" A record.
variable "route53zone" {
description = "String holding Route53 Hosted zone ID"
type = string
default = "Z06810324566743LH9RTLR"
}
resource "aws_route53_record" "www" {
zone_id = var.route53zone
name = "www.domain.com"
type = "A"
ttl = 60
records = [aws_eip.VPC_test-sP-EIP1.public_ip]
}
resource "aws_route53_record" "root" {
zone_id = var.route53zone
name = "domain.com"
type = "A"
alias {
name = aws_route53_record.www.fqdn
zone_id = var.route53zone
evaluate_target_health = false
}
}