Skip to content

Instantly share code, notes, and snippets.

@archevel
Created February 16, 2016 10:44
Show Gist options
  • Save archevel/48db152b85ad643bf33a to your computer and use it in GitHub Desktop.
Save archevel/48db152b85ad643bf33a to your computer and use it in GitHub Desktop.
Generate haproxy configuration from host entries
#!/bin/bash
set -e
CONF_FILE=$(</etc/haproxy.conf.tmpl)
echo "CONF_FILE has original content:"
echo "#####"
echo "$CONF_FILE" | tee /usr/local/etc/haproxy/haproxy.conf
echo "#####"
echo
echo "Grabing docker containers from the hostfile (using docker's subnet)"
HOSTS=$(grep -P "^172.17.[.0-9]+\t[^ _]+ .+$" /etc/hosts)
echo "HOSTS to specify backends and mappings for:"
echo "#####"
echo "$HOSTS"
echo "#####"
echo
echo "Using sed to create mappings entries for the found hosts"
MAPPINGS=$(sed "s/\(^[.0-9]*\)\t\([^ _]*\) .*$/ use_backend \2 if \{ path_beg \/\2\/ \}\n/g" <<< "$HOSTS")
echo "Appending these MAPPINGS to conf file:"
echo "#####"
printf "$MAPPINGS\n\n" | tee -a /usr/local/etc/haproxy/haproxy.conf
echo "#####"
echo
echo "Using sed to create the backend entries for the found hosts"
BACKENDS=$(sed "s/\(^[.0-9]*\)\t\([^ _]*\) .*$/backend \2 \n reqrep ^([^\\\ ]*\\\ \/)\2[\/]?(.*) \\\1\\\2\n server \2 \1:5000 maxconn 32\n/g" <<< "$HOSTS")
echo "Appending these BACKENDS to conf file:"
echo "#####"
echo "$BACKENDS" | tee -a /usr/local/etc/haproxy/haproxy.conf
echo "#####"
echo
echo "Final config file:"
echo "#####"
cat /usr/local/etc/haproxy/haproxy.conf
echo "#####"
echo Starting haproxy!
haproxy -f /usr/local/etc/haproxy/haproxy.conf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment