ansible-role-server/templates/ddns-hosts.sh

56 lines
2.0 KiB
Bash

#!/bin/sh
passwd='{{ ddns_passphrase }}'
hostname=$(hostname | tr '[:upper:]' '[:lower:]')
platform='unknown'
unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then
platform='linux'
elif [ "$unamestr" = 'FreeBSD' ]; then
platform='freebsd'
fi
ip6addr=''
ip4addr=''
if [ $platform = 'linux' ]; then
# only accept global IPv6 addresses (starting with 2 or 3)
ip6addr=$(ip -6 addr show scope global | grep inet6 | tail -1 | egrep -o '([0-9abcdef]{4}[0-9:abcdef]*)' | egrep '^[2,3]')
# filter local IPv4 address ranges (172.16.0.0/12, 10.0.0.0/8, 192.168.0.0/16)
ip4addr=$(ip -4 addr show scope global | grep inet | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | grep -Ev '172.(1[6-9]|2[0-9]|3[0-1])' | grep -Ev '10.' | grep -Ev '192.168.' | head -n 1)
elif [ $platform = 'freebsd' ]; then
ip6addr=$(ifconfig em0 | grep inet6 | tail -1 | egrep -o '([0-9abcdef]{4}[0-9:abcdef]*)')
ip4addr=$(ifconfig em0 inet | grep inet | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -n 1)
fi
echo "Current IP addresses of $hostname are: $ip4addr, $ip6addr"
if [ $ip4addr ]; then
echo "Updating IPv4 DNS entry..."
else
echo "No public IPv4 address, updating DNS entry anyway..."
fi
# API always returns 200, so check for response payload to begin with {"Success":true,
url="https://{{ ddns_server_domain }}/update?secret=$passwd&domain=$hostname&addr=$ip4addr"
statuscode=$(curl -s $url)
case "$statuscode" in
{\"Success\":true*) echo "IPv4 Success" ;;
*) (>&2 echo "IPv4 DynDNS update failed: API response:\n$statuscode") ;;
esac
if [ $ip6addr ]; then
echo "Updating IPv6 DNS entry..."
# API always returns 200, so check for response payload to begin with {"Success":true,
url="https://{{ ddns_server_domain }}/update?secret=$passwd&domain=$hostname&addr=$ip6addr"
statuscode=$(curl -s $url)
case "$statuscode" in
{\"Success\":true*) echo "IPv6 Success" ;;
*) (>&2 echo "IPv6 DynDNS update failed: API response:\n$statuscode") ;;
esac
else
echo "No public IPv6 Address, skipping DNS update."
fi