Skip to content

Instantly share code, notes, and snippets.

@ssttevee
Last active December 12, 2023 23:59
Show Gist options
  • Save ssttevee/7ebf0c48abbba13c27f395b44f76ef35 to your computer and use it in GitHub Desktop.
Save ssttevee/7ebf0c48abbba13c27f395b44f76ef35 to your computer and use it in GitHub Desktop.
#!/bin/sh
name=$1
if [[ -z "$name" ]]; then
echo "missing domain name argument"
exit 1
fi
CADDYFILE=${CADDYFILE:-/etc/caddy/Caddyfile}
if [[ -z "$(which jq)" ]]; then
missingpkgs="$missingpkgs jq"
fi
if [[ -z "$(which curl)" ]]; then
missingpkgs="$missingpkgs curl"
fi
if [[ -n "$missingpkgs" ]]; then
apk add $missingpkgs
fi
mkdir -p "$(dirname "$CADDYFILE")"
function get_ips {
curl -s -H "accept: application/dns-json" "https://1.1.1.1/dns-query?name=$name&type=a" | jq -r '.Answer | .[] | .data + " " + (.TTL | tostring)'
}
(
while [[ -f "/proc/$$/status" ]]; do
ips_and_ttls="$(get_ips)"
current_ips="$(printf "$ips_and_ttls" | awk '{ print $1 }')"
ttl="$(printf "$ips_and_ttls" | awk '{ print $2 }' | sort -rn | head -n1)"
if [[ "$prev_ips" != "$current_ips" ]]; then
cat <<EOF > "$CADDYFILE"
http://:8428 {
reverse_proxy /insert/* $(printf "$current_ips" | awk '{ print "http://" $1 ":8480" }' | tr '\n' ' ' | xargs) {
health_uri /metrics
}
reverse_proxy /select/* $(printf "$current_ips" | awk '{ print "http://" $1 ":8481" }' | tr '\n' ' ' | xargs) {
health_uri /metrics
}
}
EOF
fi
prev_ips="$current_ips"
sleep $((ttl + 5))
done
) &
while [[ ! -f "$CADDYFILE" ]]; do
sleep 1
done
exec caddy run -w -c "$CADDYFILE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment