Dynamic DNS records with Terraform and Route 53

Wouter van der Meulen
Wouter van der Meulen
Jun 18 2021
Posted in Engineering & Technology

Dynamically assign Route53 records to your AWS instances with Terraform

Dynamic DNS records with Terraform and Route 53

In this short post, I would like to introduce you to one of my favorite workflows with Terraform, dynamically adding DNS records based on instances. While many platform solutions (ex: Elastic Load Balancer) will automatically connect this for you, it's not suitable for all workflows. In this case we want to start up AMIs where each instance needs to have a specific internal URL.

Creating the instances

First things first, here's a quick reminder on how to create several instances:

# Find your latest custom AMI
data "aws_ami" "custom_ami" {
  owners = ["<Your owner id>"]

  filter {
    name   = "state"
    values = ["available"]
  }

  filter {
    name   = "tag:Name"
    values = ["Notificare Custom"]
  }

  most_recent = true
}

resource "aws_instance" "custom_cluster" {
  count                = 3
  ami                  = data.aws_ami.custom_ami.id
  instance_type        = "r6g.micro"

  tags = {
    Name               = "custom_instance_${count.index}"
  }
}

Creating DNS records

In order to work with the created instances effectively, we need to turn it into a list of IP addresses:

locals {
  cystin_servers = tolist([
    for server in aws_instance.custom_cluster :
    server.private_ip
  ])
}

Now that we've done that, we can start creating DNS records for our cluster. Simply create a Route 53 resource and use the count function to create as many records as there are instances. We'll populate the records using the local we've just created.

In our case, we have a manually created zone in Route 53. We'll simply fill in the zone's id in the resource. For production use, you'll probably want to use a variable.

resource "aws_route53_record" "www" {
  count = length(local.custom_cluster)

  zone_id = "<Choose your zone>"
  name    = "instance-${count.index + 1}.notifica.re"
  type    = "A"
  ttl     = "300"
  records = [local.custom_cluster[count.index]]
}

Conclusion

And there we have it, a simple guide on how to create Route 53 records with Terraform. Being able to quickly modify DNS records without going into the GUI is invaluable. Obviously, you could use this for infrastructure that is way more complicated than just 3 connected instances.

As always, don't feel shy to contact us if you have any question, suggestion or correction to this post. Get in touch via our Support Channel.

Keep up-to-date with the latest news
Emerce
Capterra
ISO27001