Last active
February 21, 2017 09:26
-
-
Save YarGnawh/86c344ea4a4a0ffc9479 to your computer and use it in GitHub Desktop.
AWS EC2 Route53 Update CNAME using JSON USER_DATA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Write to /usr/local/ec2/ec2-host-update.sh | |
# Execute chmod 755 ec2-host-update.sh | |
# Append /usr/local/ec2/ec2-host-update.sh to /etc/rc.local | |
# Referenced: http://realguess.net/2013/12/06/amazon-route-53-via-command-line/ | |
if ! type "aws" > /dev/null; then | |
echo "Requires AWS CLI" | |
else | |
USER_DATA=`/usr/bin/curl -s http://169.254.169.254/latest/user-data` | |
PUBLIC_HOST_NAME=`curl -s http://169.254.169.254/latest/meta-data/public-hostname` | |
if [[ $USER_DATA == "" ]] || [[ $USER_DATA == *404* ]]; then | |
echo "Metdata user data invalid" | |
exit 0 | |
fi | |
echo "Metdata user data : $USER_DATA" | |
USER_DATA_HOST_ZONE_ID=`echo $USER_DATA | python -c 'import json,sys; obj=json.load(sys.stdin); print obj["zoneId"];'` | |
USER_DATA_HOST_RECORD_NAME=`echo $USER_DATA | python -c 'import json,sys; obj=json.load(sys.stdin); print obj["recordName"];'` | |
if [[ $USER_DATA_HOST_ZONE_ID != "" ]] && [[ $USER_DATA_HOST_RECORD_NAME != "" ]]; then | |
# create change batch file | |
cat<<EOF > /usr/local/ec2/change.json | |
{ | |
"Comment": "Updating Public Host Record", | |
"Changes": [ | |
{ | |
"Action": "UPSERT", | |
"ResourceRecordSet": { | |
"Name": "$USER_DATA_HOST_RECORD_NAME", | |
"Type": "CNAME", | |
"TTL": 300, | |
"ResourceRecords": [ | |
{ | |
"Value": "$PUBLIC_HOST_NAME" | |
} | |
] | |
} | |
} | |
] | |
} | |
EOF | |
# aws access key and secret needs to be setup beforehand | |
aws route53 change-resource-record-sets --hosted-zone-id "$USER_DATA_HOST_ZONE_ID" --change-batch file:///usr/local/ec2/change.json | |
# remove catch batch file | |
rm /usr/local/ec2/change.json | |
fi | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"zoneId":"HGD235235332M", | |
"recordName":"host.ofunc.com" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment