Add/Edit DNS zone records on AWS Route53

Route53 is AWS’s DNS service. Last year I worked on a building a custom auto scaling solution on AWS using AWS AutoScale for EC2 servers. In this, I had a custom boot script that executes every time a new server is added to the cluster. And the script also generates a unique and sequential hostname and create a valid DNS record in Route53. For example, the first server will create a FQDN such as server1.example.com and the 5th server in the cluster will create server5.example.com

Since the servers are in the autoscale group, each day new servers get created or destroyed based on the configuration (CPU load etc)

The following bash snippetĀ is used to create DNS zone records in the script

function createDNS {
HOSTNAME=$1
IP=$2
ZONEID=ZNTLWLDUBLUV113 # Route53 zone id of your website
TMPFILE=$(mktemp /tmp/temporary-file.XXXXXXXX)
cat > ${TMPFILE} << EOF
{
  "Comment":"Custom Inserted",
  "Changes":[
    {
      "Action":"UPSERT",
      "ResourceRecordSet":{
        "ResourceRecords":[
          {
            "Value":"${IP}"
          }
        ],
        "Name":"${HOSTNAME}",
        "Type":"A",
        "TTL":300
      }
    }
  ]
}
EOF
# Update the Hosted Zone record
aws route53 change-resource-record-sets \
    --hosted-zone-id ${ZONEID} \
    --change-batch file://"${TMPFILE}"
}

Note: In order for this to work, you need the following

  1. AWS CLI installed on the server.
  2. The EC2 instance must have a IAM role that has the permission to modify the Route53 domain

This function will help you to insert a DNS record simply by calling

createDNS server1.example.com 127.0.0.1

If you want to know what is your private IP of the EC2 machine and setup a FQDN to it, use the following

#Generate hostname first and set it using hostnamectl set-hostname

HOSTNAME=$(hostname)
IP=$(wget -qO- http://169.254.169.254/latest/meta-data/local-ipv4)
createDNS ${HOSTNAME} ${IP}

Hope you find this useful

Leave a Reply

Your email address will not be published. Required fields are marked *