Skip to content

Instantly share code, notes, and snippets.

@gerhardqux
Last active April 20, 2018 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerhardqux/9f2343e3e256ebcf1ad1525853ec0f8d to your computer and use it in GitHub Desktop.
Save gerhardqux/9f2343e3e256ebcf1ad1525853ec0f8d to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# adapted from https://github.com/kvz/nsfailover/blob/master/nsfailover.sh
[ -z "${NS_FILE}" ] && NS_FILE="/etc/resolv.conf" # Where to write resolving conf
nameservers=""
function ns_healthy() {
local nserver="${1}"
result="$(dig @${nserver} +time=3 +tries=1 +short qrux.nl)"
exitcode="${?}"
if [ -z "${result}" ] || [ "${exitcode}" -ne 0 ]; then
echo "no"
logger -t nsfail -p local0.warn "can't reach nameserver: " ${ns}
else
echo "yes"
fi
}
function nameserver() {
local ns="${1}"
if [[ $(ns_healthy ${ns}) = "yes" ]]; then
resolvconf+=$'\n'"nameserver ${ns}"
nameservers+=${ns}\
else
resolvconf+=$'\n'"#nameserver ${ns}"
fi
}
set -ue
resolvconf="options timeout:1 attempts:2 rotate"
nameserver 1.1.1.1
nameserver 8.8.8.8
#nameserver 127.0.0.1
nameserver 8.8.4.4
# Load current config
current="$(cat ${NS_FILE})" || true
# Is the config updated?
if [ "${resolvconf}" != "${current}" ]; then
curdate="$(date -u +"%Y%m%d%_H%M%S")"
cp "${NS_FILE}" ${NS_FILE}.bak-${curdate}
tmpfile="${NS_FILE}.tmp"
echo "$resolvconf" > $tmpfile
mv $tmpfile $NS_FILE
logger -t nsfail -p local0.warn "set nameservers to: " $nameservers
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment