You want to run an OpenVPN server on a debian-like system with a dynamic IP address (f.i. behind a consumer cable modem access)
You need to provide a fixed IP address in the openvpn configuration
Ensure the OpenVPN configuration is updated with each IP address change and reload the server
In order to run an application upon IP address change, you need to create a hook inside /etc/dhcp/dhclient-exit-hooks.d .
Create a file called /etc/dhcp/dhclient-exit-hooks.d/openvpn with this content :
#!/bin/sh
RUN="yes"
LOGFILE=/var/log/dynopenvpn.log
OVPNCFG=/etc/openvpn/server.conf
export LC_ALL=C
if [ "$RUN" = "yes" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S :') DynOpenVPN called" >>$LOGFILE
if [ "x$reason" = "x" ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S :') Not called by dhclient" >>$LOGFILE
new_ip_address=`ip -4 -o addr | grep eth0 |awk '{print $4}' | sed 's@/.*@@'`
else
echo "$(date '+%Y-%m-%d %H:%M:%S :') dhclient $reason" >>$LOGFILE
fi
if [ "x$new_ip_address" != "x" ]; then
echo -n "$(date '+%Y-%m-%d %H:%M:%S : ')" >>$LOGFILE
current_ip=`awk '$1=="local" {print $2}' <$OVPNCFG`
if [ "$current_ip" != "$new_ip_address" ]; then
sed -i -e "s/local .*/local $new_ip_address/" $OVPNCFG
echo -n "New config file : " >>$LOGFILE
head -1 $OVPNCFG >>$LOGFILE
systemctl restart [email protected]
else
echo "Not updating server.conf as $new_ip_address is already registered" >>$LOGFILE
fi
fi
fi