Created
October 3, 2013 13:02
-
-
Save borisguery/6809466 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env bash | |
| VERBOSE=1 | |
| IPS_FILE="/tmp/elb_ips" | |
| BACKEND_VCL="/etc/varnish/backend.vcl" | |
| # Does not keep newlines, but it's ok | |
| read -r -d '' BACKEND_TEMPLATE <<'EOF' | |
| backend internal_elb_{ELB_NUM} { | |
| .host = "{ELB_IP}"; | |
| .port = "80"; | |
| } | |
| EOF | |
| mapfile ELB_IPS < <(dig +short $1 | grep -v '[[:alpha:]]' | sort -u) | |
| function write_ip_to_file { | |
| rm $IPS_FILE | |
| IPS=("${@}") | |
| for IP in ${IPS[@]}; do | |
| echo $IP >> $IPS_FILE | |
| done | |
| } | |
| function verbose { | |
| if [ $VERBOSE -eq 1 ]; then | |
| echo $1 >&2 | |
| fi | |
| } | |
| if [ ! -f "$IPS_FILE" ]; then | |
| verbose "ELB IPS are not stored yet, creating..." | |
| write_ip_to_file ${ELB_IPS[@]} | |
| elif ! diff -q <(printf "%s" "${ELB_IPS[@]}") $IPS_FILE > /dev/null; then | |
| verbose "IPS have changed, updating. | |
| write_ip_to_file ${ELB_IPS[@]} | |
| tmp_file=$(tempfile) | |
| verbose "Creating backends..." | |
| for idx in ${!ELB_IPS[@]}; do | |
| ip=$(echo ${ELB_IPS[$idx]} | tr -d '\n ') | |
| DEFINED_BACKEND=$(echo $BACKEND_TEMPLATE | sed -e "s/{ELB_NUM}/$idx/" -e "s/{ELB_IP}/$ip/") | |
| verbose "+ $DEFINED_BACKEND" | |
| echo $DEFINED_BACKEND >> $tmp_file | |
| done | |
| verbose "Creating director..." | |
| echo "director elb round-robin {" >> $tmp_file | |
| for idx in ${!ELB_IPS[@]}; do | |
| echo "{ .backend = internal_elb_$idx; }" >> $tmp_file | |
| done | |
| echo "}" >> $tmp_file | |
| verbose "Moving new backend file" | |
| mv $tmp_file $BACKEND_VCL | |
| verbose "Reloading Varnish" | |
| service varnish reload | |
| else | |
| verbose "ELB ips have not changed, exiting..." | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment