2

Updating Route53 records after EC2 instance restart

 3 years ago
source link: http://www.linux-admins.net/2017/02/updating-route53-records-after-ec2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Updating Route53 records after EC2 instance restart

If you are not using Elastic IPs for your EC2 instances, chances are stopping and starting the server (as opposed to just restarting it) will result in different IPs after the instance comes back online. If you have A records pointing to those IPs in Route53 you will need a way to update them.
There are few different solution to work around this problem. I decided to whip up a quick script that runs from rc.local on EC2 instances that have the appropriate IAM role to update Route53 records. After the script is executed, it will automatically gather the new Public IP and update the DNS record for it in Route53. Hackish you say, perhaps, but it is a good primer on using the AWS CLI. The script follows:

#!/bin/bash

RECORD_SET="/tmp/change-resource-record-sets.json" HOSTNAME=$(hostname -f) PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4) # Adjust the domain name as needed HOSTED_ZONE=$(hostname -d | awk -F"." '{print $(NF-2)"."$(NF-1)"."$(NF)}') ZONE_ID=$(aws route53 list-hosted-zones | jq --arg hosted_zone $HOSTED_ZONE. '.HostedZones[] | select(.Name == $hosted_zone) | .Id' | awk -F"/" '{print $3}' | tr -d "\"") RECORD_TYPE=$(aws route53 list-resource-record-sets --hosted-zone-id $ZONE_ID --query "ResourceRecordSets[?Name == '$HOSTNAME.']" | jq ".[].Type" | tr -d "\"")

if [ -e "$RECORD_SET" ] then rm -f $RECORD_SET fi

echo "Updating resource record set" echo " { \"Comment\": \"Update record to reflect new public IP address\", \"Changes\": [ { \"Action\": \"UPSERT\", \"ResourceRecordSet\": { \"Name\": \"$HOSTNAME.\", \"Type\": \"$RECORD_TYPE\", \"TTL\": 300, \"ResourceRecords\": [ { \"Value\": \"$PUBLIC_IP\" } ] } } ] }" | tee -a /tmp/change-resource-record-sets.json

CHANGE_ID=$(aws route53 change-resource-record-sets --hosted-zone-id $ZONE_ID --change-batch file:///$RECORD_SET | jq ".ChangeInfo.Id" | awk -F"/" '{print $3}' | tr -d "\"") CHANGE_STATUS=$(aws route53 get-change --id $CHANGE_ID | jq ".ChangeInfo.Status" | tr -d "\"") declare -i COUNT=0

while [ "$CHANGE_STATUS" == "PENDING" ] do COUNT=COUNT+1 if [ "$COUNT" -ge 6 ] then echo "Update timed out, exiting..." exit 1 fi sleep 10 CHANGE_STATUS=$(aws route53 get-change --id $CHANGE_ID | jq ".ChangeInfo.Status" | tr -d "\"") done

echo "Record updated!"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK