Skip to content

Instantly share code, notes, and snippets.

@rduplain
Last active June 10, 2022 13:23
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rduplain/d3f42127cbe2c12ea1e4 to your computer and use it in GitHub Desktop.
Save rduplain/d3f42127cbe2c12ea1e4 to your computer and use it in GitHub Desktop.
Rewrite haproxy configuration and reload service.
# Edit this file then run `update-haproxy haproxy-servers.cfg`.
# Alternatively, use a shell pipeline to build server list `... | update-haproxy`.
server demo1 127.0.0.1:8001 check cookie demo1 weight 100
server demo2 127.0.0.1:8002 check cookie demo2 weight 100
server demo3 127.0.0.1:8003 check cookie demo3 weight 0
server demo4 127.0.0.1:8004 check cookie demo3 weight 0
global
log 127.0.0.1 local0 notice
chroot /var/lib/haproxy
maxconn 10000
user haproxy
group haproxy
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 3s
timeout client 60s
timeout server 60s
retries 3
option redispatch
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
listen demo 0.0.0.0:80
mode http
stats enable
stats uri /__demo__?stats
stats realm Authentication\ Required
stats auth ops:ov9fifVEMmeDXLFLocGjAhXC
balance roundrobin
option httpclose
option forwardfor
cookie demo insert
#!/bin/bash
# Rewrite haproxy configuration and reload service.
#
# Provide a file with haproxy config server lines, or stdin:
#
# usage: update-haproxy [FILE_WITH_SERVER_LINES]
#
# NOTE: Assumes pre-loaded base haproxy.cfg is ready to be appended
# with indented server lines, with 4-spaces of indentation.
# File with server lines should not be indented.
#
# Uses 'haproxy.cfg' file next to 'update-haproxy' as pre-loaded base.
# Exit immediately if a command error or non-zero return occurs.
set -e
# The name of this executable.
PROG="$( basename "${BASH_SOURCE[0]}" )"
# Directory containing this executable.
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Path to production haproxy.cfg.
HAPROXY_CFG=${HAPROXY_CFG:-/etc/haproxy/haproxy.cfg}
# Command to reload haproxy.
RELOAD_HAPROXY=${RELOAD_HAPROXY:-service haproxy reload}
# Base configuration for concatenation with given servers.
BASE_CFG=$DIR/haproxy.cfg
if [ ! -e $BASE_CFG ]; then
echo "$PROG: missing $BASE_CFG; where did it go?" >&2
exit 2
fi
SERVER_CFG=$1
shift
# Use stdin if no server configuration file is given.
if [ -z "$SERVER_CFG" ]; then
SERVER_CFG=-
fi
(
cat $BASE_CFG
cat $SERVER_CFG |\
while read -r line; do
echo " $line"
done
) > $HAPROXY_CFG
$RELOAD_HAPROXY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment