Ubuntu – Systemd-networkd: Run script after DHCP client aqcuires new address

dhcpdyndnssystemdsystemd-networkdUbuntu

I am on ubuntu 18.04 server. I need to run a script that updates an IP address on CloudFlare (kind of DynDNS script). In previous versions I could do this with a DHCLIENT exit hooks for the interface enp1s0.

However, systemd now uses their own build-in DHCP client. How can I write a systemd unit that executes my bash script as soon as a new IP address is provided to the DCHP client?

Systemd is managing the interface enp1s0:

#sudo  systemctl status systemd-networkd
● systemd-networkd.service - Network Service
   Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled-runtime; vendor preset: enabled)
   Active: active (running) since Tue 2018-09-18 01:54:16 +08; 10h ago
     Docs: man:systemd-networkd.service(8)
 Main PID: 878 (systemd-network)
   Status: "Processing requests..."
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/systemd-networkd.service
           └─878 /lib/systemd/systemd-networkd

Sep 18 01:54:27 xxx systemd-networkd[878]: enp1s0: Configured

Best Answer

I don't know of any systemd solution, but you can monitor changes to interfaces efficiently with ip monitor and pipe the output into a script that looks for the changes that interest you. For example, if I do

$ ip monitor address dev enp3s0

then add a new alias address to interface enp3s0 I get the line

2: enp3s0    inet 192.168.77.77/24 brd 192.168.77.255 scope global enp3s0:1
       valid_lft forever preferred_lft forever

I presume you would see something similar for dhcp changes.

If you prefer, you can write a C program to do the same, see this ipevent.c.