Skip to content

Instantly share code, notes, and snippets.

@wiedehopf
Last active June 16, 2024 18:01
Show Gist options
  • Save wiedehopf/cee10f72f7cbceae81021407aa4368bf to your computer and use it in GitHub Desktop.
Save wiedehopf/cee10f72f7cbceae81021407aa4368bf to your computer and use it in GitHub Desktop.
Haproxy: Ugly bash script to update ACL entries without reloading haproxy

This would be in the haproxy config:

acl whitelist src -f /etc/haproxy/whitelist.txt

Then you could update the file and then to update haproxy without restarting it using the update-table.sh script:

./update-table.sh whitelist.txt
#!/bin/bash
# shellcheck disable=2094
SOCKET="/run/haproxy-stats.sock"
hacommand() { echo "$@" | socat stdio "UNIX-CLIENT:$SOCKET"; }
hacommand_verbose() { echo "$@" ; echo "$@" | socat stdio "UNIX-CLIENT:$SOCKET"; }
acl=/etc/haproxy/$1
if [[ -n "$2" ]]; then
if grep -qsF -e "$2" "$acl" &>/dev/null; then
echo "already in list: $2"
else
echo "$2" >> "$acl"
fi
fi
WD=/run/updatetable
mkdir -p "$WD"
live="$WD/live"
disk="$WD/disk"
add="$WD/add"
del="$WD/del"
# remove key from live acl, sort, remove duplicates, remove empty lines
hacommand show acl "$acl" | cut --complement -d ' ' -f 1 | sort | uniq | awk 'NF' > "$live"
# sort file on disk, remove comments and empty lines, remove duplicate lines, remove leading spaces
sort < "$acl" | awk '/^[^#]/' | awk 'NF' | sed -e 's/^ *//' | uniq > "$disk"
diff "$live" "$disk" | grep -E '^> ' | sed -e 's/^> *//' > "$add"
diff "$disk" "$live" | grep -E '^> ' | sed -e 's/^> *//' > "$del"
# add entries missing in live
echo Adding ............
while IFS='' read -r line; do
line="${line// /\ }"
hacommand_verbose add acl "$acl" "$line"
done < "$add"
echo .............. done.
# delete entries missing on disk
echo Deleting ..........
while IFS='' read -r line; do
line="${line// /\ }"
hacommand_verbose del acl "$acl" "$line"
done < "$del"
echo .............. done.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment