Last active
January 11, 2020 22:54
-
-
Save rterbush/89208a607aea03322869 to your computer and use it in GitHub Desktop.
Create Route53 A records using IAM profile with route53 access
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/sh | |
# bootstrap script that runs on every system boot called via AWS instance user-data | |
# via 'curl -s http://169.254.169.254/latest/user-data | /bin/sh 2>&1' | |
# Make sure only root can run our script | |
if [ "$(id -u)" != "0" ]; then | |
echo "This script must be run as root" 1>&2 | |
exit 1 | |
fi | |
# route53 IP assignment requires an assigned IAM profile/role to the callign | |
# EC2 instance that includes the following policy | |
# { | |
# "Version": "2012-10-17", | |
# "Statement": [ | |
# { | |
# "Effect": "Allow", | |
# "Action": [ | |
# "route53:ChangeResourceRecordSets", | |
# "route53:GetHostedZone", | |
# "route53:ListResourceRecordSets" | |
# ], | |
# "Resource": "arn:aws:route53:::hostedzone/<zone-id>" | |
# }, | |
# { | |
# "Effect": "Allow", | |
# "Action": [ | |
# "route53:GetChange", | |
# "route53:ListHostedZones" | |
# ], | |
# "Resource": "*" | |
# } | |
# ] | |
# } | |
TTL=600 | |
EC2CMD='aws ec2 describe-tags' | |
APIURL='http://169.254.169.254/latest/meta-data' | |
AVAILZONE=$(curl -s ${APIURL}/placement/availability-zone) | |
REGION=${AVAILZONE%[a-z]} | |
RESOURCEID=$(curl -s ${APIURL}/instance-id) | |
MNAME=$(${EC2CMD} --region=${REGION} --filters "Name=resource-id,Values=${RESOURCEID}" "Name=key,Values=Name" --output=text | cut -f5 | tr -d '\n') | |
DOMAIN='example.com' | |
HOSTNAME=${MNAME%.${DOMAIN}} | |
HOSTIP=$(curl -s ${APIURL}/local-ipv4) | |
hostname ${HOSTNAME} | |
echo ${HOSTNAME} > /etc/hostname | |
cat<<EOF > /etc/hosts | |
# This file is automatically genreated by ec2-hostname script | |
127.0.0.1 localhost | |
${HOSTIP} ${HOSTNAME}.${DOMAIN} ${HOSTNAME} | |
# The following lines are desirable for IPv6 capable hosts | |
::1 ip6-localhost ip6-loopback | |
fe00::0 ip6-localnet | |
ff00::0 ip6-mcastprefix | |
ff02::1 ip6-allnodes | |
ff02::2 ip6-allrouters | |
ff02::3 ip6-allhosts | |
EOF | |
# Create a new CNAME record on Route 53, replacing the old entry if nessesary | |
if [ ! -z "${HOSTNAME}" ] && [ ! -z "${HOSTIP}" ]; then | |
cli53 rrcreate "${DOMAIN}" "${HOSTNAME}" A "${HOSTIP}" --replace --ttl "${TTL}" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saweet!