Skip to content

Instantly share code, notes, and snippets.

@nkwhr
Created May 16, 2014 09:52
Show Gist options
  • Save nkwhr/fd0468c0d1cdb11a6b02 to your computer and use it in GitHub Desktop.
Save nkwhr/fd0468c0d1cdb11a6b02 to your computer and use it in GitHub Desktop.
A handler script for updating /etc/hosts with Serf.
#!/bin/sh
set -e
export PATH=/usr/local/bin:/usr/bin:/bin
read name address role tags
file=/etc/hosts
tmp_file=/tmp/hosts.tmp
lock_file=/tmp/hosts.lock
active_members=$(serf members | grep 'alive' | cut -d ':' -f1 | awk '{print $2"\t"$1}')
while [ -f $lock_file ] ; do sleep 1 ; done
touch $lock_file
if [ $SERF_EVENT = 'member-join' ] ; then
hosts=$(grep -v '^#' $file)
echo -e "$hosts\n$active_members" | sort -n | uniq > $tmp_file
mv $tmp_file $file \
&& echo "$name successfully added to $file"
elif [ $SERF_EVENT = 'member-leave' -o $SERF_EVENT = 'member-failed' ] ; then
hosts=$(grep -v '^#' $file | grep -v "^$address[[:blank:]]")
echo -e "$hosts\n$active_members" | sort -n | uniq > $tmp_file
mv $tmp_file $file \
&& echo "$name successfully removed from $file"
fi
rm -f $lock_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment