You haven't indicated your Ubuntu version. The following was tested on Ubuntu 22.04 Server.
This can be accomplished by creating a "drop-in" configuration file for your interface, which will add or override your network configurations.
Per systemd.network(5):
Along with the network file foo.network, a "drop-in" directory
foo.network.d/ may exist. All files with the suffix ".conf" from
this directory will be merged in the alphanumeric order and
parsed after the main file itself has been parsed. This is useful
to alter or add configuration settings, without having to modify
the main configuration file. Each drop-in file must have
appropriate section headers.
An example...
You haven't included your Netplan YAML configuration file, so I'll use the following:
$ cat /etc/netplan/00-install-config.yaml
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: true
In this instance, the network interface is eth0
. You will need to substitute your interface in place of eth0
in the below commands.
1. Create drop-in directory
When the Netplan YAML file is parsed, the following file is created: /run/systemd/network/10-netplan-eth0.network
.
The drop-in directory name needs to match this filename with the addition of a ".d" suffix:
sudo mkdir /etc/systemd/network/10-netplan-eth0.network.d
2. Create the configuration file:
In this directory, create a configuration file ending in ".conf". The name doesn't matter, just the suffix.
sudo touch /etc/systemd/network/10-netplan-eth0.network.d/10-netplan-eth0.network.conf
3. Edit as follows:
# Drop-in configuration for 10-netplan-eth0.network
[Network]
KeepConfiguration=dhcp-on-stop
4. Restart systemd-networkd
:
sudo systemctl restart systemd-networkd
For completeness for others, I'm including the section regarding the KeepConfiguration=
key.
Per systemd.network(5):
KeepConfiguration=
Takes a boolean or one of "static", "dhcp-on-stop", "dhcp".
When "static", systemd-networkd will not drop static
addresses and routes on starting up process. When set to
"dhcp-on-stop", systemd-networkd will not drop addresses and
routes on stopping the daemon. When "dhcp", the addresses and
routes provided by a DHCP server will never be dropped even
if the DHCP lease expires. This is contrary to the DHCP
specification, but may be the best choice if, e.g., the root
filesystem relies on this connection. The setting "dhcp"
implies "dhcp-on-stop", and "yes" implies "dhcp" and
"static". Defaults to "dhcp-on-stop" when systemd-networkd is
running in initrd, "yes" when the root filesystem is a
network filesystem, and "no" otherwise.