Skip to content

Instantly share code, notes, and snippets.

@dominics
Last active February 7, 2017 02:32
Show Gist options
  • Save dominics/2178a1f04fc25d3b55457991808b6a26 to your computer and use it in GitHub Desktop.
Save dominics/2178a1f04fc25d3b55457991808b6a26 to your computer and use it in GitHub Desktop.
"hostfile" an AWS ALB
#!/bin/bash
set -e
set -o pipefail
if [ $EUID -ne 0 ]; then
exec sudo "$0" "$@"
fi
readonly hostname=$1
readonly target=$2
if [[ -z "$hostname" || -z "$target" ]]; then
echo "Usage: $0 <hostname-to-alias> <elb-dns-name-to-target>" >&2
exit 1
fi
echo "Updating /etc/hosts entry for $hostname..."
IP=$(dig +short $target a | sort | head -n 1)
if [ $? -ne 0 -o -z "$IP" ]; then
echo "Could not get IP address" >&2
exit 3
fi
# Update the hosts file
if test -n "$IP"; then
hash puppet > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
echo "Setting it to $IP via \`puppet resource host $hostname ip=$IP\`"
puppet resource host $hostname ip=$IP
else
echo "Setting it to $IP via tmpfile"
tmpfile=$(mktemp)
chown root: $tmpfile
chmod 644 $tmpfile
grep -v "\s$hostname\$" /etc/hosts > $tmpfile
echo -e "$IP\t$hostname" >> $tmpfile
mv $tmpfile /etc/hosts
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment