Skip to content

Instantly share code, notes, and snippets.

@ambakshi
Last active July 25, 2021 05:39
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ambakshi/8d2276af73cc896cab5f to your computer and use it in GitHub Desktop.
Save ambakshi/8d2276af73cc896cab5f to your computer and use it in GitHub Desktop.
Add all instances in an autoscaling group to an equivalently named dns entry.
#!/bin/bash
#
# Get all IPs from an autoscale group and update set the local ip as
# equal weight A entries (round robin dns). Takes autoscale group as
# parameter.
#
# Amit Bakshi
# 10/21/2014
#
ZONE_ID=YOURZONEID
DOMAIN=yourdomain.com
[ -n "$1" ] || {
echo >&2 "Usage: $0 <auto-scaling-group>"
exit 2
}
asg_ips () {
local instance_ids="$(aws autoscaling describe-auto-scaling-groups \
--auto-scaling-group-names "$1" \
--query 'AutoScalingGroups[*].Instances[*].[InstanceId]' --output text)"
aws ec2 describe-instances --instance-ids $instance_ids \
--query 'Reservations[*].Instances[*].[PrivateIpAddress]' --output text
}
gen_json () {
local private_ips=($(asg_ips "$1"))
cat <<EOF
{
"Comment": "Modifying autoscale group $1 record for the zone.",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "$1.${DOMAIN}.",
"Type": "A",
"TTL": 300,
"ResourceRecords": [
EOF
local -i count=${#private_ips[@]}
for ((i=0 ; i < $count - 1 ; i ++)); do
cat <<EOF
{
"Value": "${private_ips[$i]}"
},
EOF
done
cat <<EOF
{
"Value": "${private_ips[(( $count - 1 ))]}"
}
EOF
cat <<EOF
]
}
}
]
}
EOF
}
gen_json "$1" > /tmp/${1}.json
aws route53 change-resource-record-sets --hosted-zone-id $ZONE_ID --change-batch file:///tmp/${1}.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment