systemd-networkd is the network manager that ships inside systemd. It reads plain-text INI unit files from /etc/systemd/network: a .network file decides what happens to the links it matches — addresses, routes, DHCP behaviour, enslavement to a master — a .netdev file creates a virtual device such as a bond, a VLAN or a bridge, and a .link file, applied by systemd-udevd rather than by the daemon, renames or reconfigures the device itself before any of that. The networkctl command exposes the running state: reload the files, reconfigure a link, bring one up or down, renew a lease. On Ubuntu server it is the backend netplan renders into, which means even hosts that "use netplan" end their configuration journey in exactly these unit files.
Reemote is a pure-Python configuration-management library. Instead of a domain-specific language, you write an ordinary Python generator that yields operations against a host, gather typed facts from the target, and await a two-phase run that previews the whole plan before it changes anything. The systemd_networkd module is written in that spirit: it owns the unit files under /etc/systemd/network and the networkctl calls that act on them, and nothing else. It needs no agent, no interpreter and no template file on the managed machine — only the systemd every Linux distribution already ships, plus a POSIX shell and an SSH connection.
This article builds a set of examples that write static units, pin down DHCP lease behaviour, stage a .link file and layer a bond, a VLAN and a bridge over them, then read the daemon back, drive it directly and clean up — and runs every one of them against a persistent Ubuntu host.
Try the canonical example first
Install Python 3.13 or newer and Docker or Podman. The connector requires you to name the CLI explicitly; there is no default.
uv venv .venv
source .venv/bin/activate
uv pip install reemote
Save this as hello.py. It is the canonical example configured for Podman. The offline pytest suite simulates the connector, and the example was also verified live with Podman. Change both docker_cmd values to "docker" if that is your local CLI.
# hello.py
import asyncio
from reemote import files, format_log, format_plan, op, run
INVENTORY = [
{
"host": "demo0",
"family": "Alpine",
"connection": {
"connector": "docker",
"identifier": "alpine:3.20",
"docker_cmd": "podman",
},
},
{
"host": "demo1",
"family": "Alpine",
"connection": {
"connector": "docker",
"identifier": "alpine:3.20",
"docker_cmd": "podman",
},
},
]
def deploy(host):
yield op(
files.install,
name="Write a greeting",
content="Hello from reemote!\n",
dest="/tmp/reemote-hello.txt",
mode="0644",
)
yield op(
files.install,
name="Record the host name",
content=f"written on {host.name}\n",
dest="/tmp/reemote-host.txt",
mode="0644",
)
async def main():
plans, report, _ = await run(INVENTORY, deploy, dry=True)
print("== Dry run ==")
print(format_plan(plans))
assert report is None
_, report, _ = await run(INVENTORY, deploy)
print("\n== Applied ==")
assert report is not None
print(format_log(report))
asyncio.run(main())
Run it with python hello.py. The dry run connects to both containers and reads real state, but sends no mutating deploy commands inside them. The connector may still create, commit, and remove its temporary containers. The apply then advances through the two operations in lockstep: both hosts finish writing the greeting before either starts recording its name.
Verified output from Podman is shown below. The dry-run plan is host-major, while the apply log is step-major: both Write a greeting entries appear before either Record the host name entry.
== Dry run ==
demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
== Applied ==
demo0: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo1: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-2e52d4f8373a608a/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-2e52d4f8373a608a/content /tmp/reemote-hello.txt && chmod 644 /tmp/reemote-hello.txt && rm -rf /tmp/reemote-install-2e52d4f8373a608a'
demo0: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
demo1: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
$ scp <files install> -> /tmp/reemote-install-8c7265455d37e471/content
$ sh -c 'mkdir -p /tmp && cp /tmp/reemote-install-8c7265455d37e471/content /tmp/reemote-host.txt && chmod 644 /tmp/reemote-host.txt && rm -rf /tmp/reemote-install-8c7265455d37e471'
An image identifier creates a throwaway container for each host. On close, Reemote commits it to a new image and removes the container. That makes every run start fresh; idempotence is demonstrated later against an existing container instead.
Unlike the throwaway-container quickstart, the migration examples below reuse the same Ubuntu hosts, so repeated runs demonstrate convergence against persistent host state.
How systemd-networkd configures a link
A unit file is short enough to read at a glance — an optional header comment, a [Match] section that selects links, and the sections that describe what to do with them:
[Match]
Name=eth1
[Network]
Address=10.30.0.11/24
Gateway=10.30.0.1
DHCP=no
Five properties of that arrangement decide how an automation tool has to treat it.
-
One directory holds three kinds of file. A
.networkfile configures links that already exist. A.netdevfile creates a virtual device:[NetDev] Kind=bond(orvlan,bridge) plus the kind's own section —[Bond],[VLAN],[Bridge]. A.linkfile is not read by networkd at all: it belongs to systemd-udevd, renames the device and sets its MAC and MTU at udev time, before any.networkcan match the new name. A tool that manages all three has to know which writes a reload actually picks up, and which it does not. -
Files match links; they do not name them.
[Match]selects interfaces byName=,Path=,MACAddress=,Type=and more. Every matching.networkapplies to a link, and when several files match the same one their settings merge in filename order — which is why units carry numeric prefixes. There is no single "configuration for eth1"; there is a set of files, each of which may claim a set of links. -
The daemon reads when you tell it to. Dropping a file into
/etc/systemd/networkchanges nothing untilnetworkctl reloadre-reads the units and reconfigures every link they match.networkctl reconfigure <link>pushes the already-loaded configuration onto one named link without re-reading any file;networkctl up/downflip the kernel'sIFF_UPflag;networkctl renewasks the DHCP server for a fresh lease. None of this restarts the daemon, and none of it needsdaemon-reload— networkd notices its own files through inotify, butreloadis the deterministic verb. -
Reading needs no root; writing does. Unit files are conventionally
root:rootmode0644, so an unprivileged login can list and read everything in/etc/systemd/networkwhile every change goes through the escalation tool. That is the opposite of netplan's0600drop-ins, and it means the facts here are cheap. -
On Ubuntu, netplan renders into
/run.netplan generatewrites backend unit files into the volatile/run/systemd/network, which is wiped at every boot and whichnetworkctlhappily matches links against. The directory this article's module owns —/etc/systemd/network— is the hand-managed one, and the two coexist; a.networkthat matches an interface netplan already claims competes with the rendered file, so every example here matches interfaces the vendor configuration does not claim.
The systemd.network(5) manual page covers the grammar in full, and the references at the end list the further reading this article's shape follows.
The Reemote systemd_networkd module
The systemd_networkd module answers the four questions worth asking about a host, and each answer is one fact. NetworkdUnits lists every unit under /etc/systemd/network as filename to kind/path/mode in a single shell round trip. NetworkdUnitFile returns one named file's raw text — byte-exact, absent distinguished from empty — and it is the read-back every write is judged against. NetworkdLinks projects networkctl list --json=short into per-interface rows: the administrative and operational states, the kernel up flag, the MAC, the addresses in CIDR form, and the .network file the link actually matched — which on a netplan host lives under /run/systemd/network, so you can see which rendered file won even though the module does not manage it. NetworkdConfig flattens the effective networkd.conf plus drop-ins into Section.Key values; on an untouched host it reads empty, because the stock file comments every row out. None of the four needs elevation.
Its operations are one write family and three verbs. network_unit owns a single unit file by bare name: it compares the wanted text against what NetworkdUnitFile reads back, and only on a real difference spools the content to a /tmp directory as the login user and installs it in one elevated step as root:root mode 0644 — then follows the write with networkctl reload, chained by the operation itself and only for .network and .netdev kinds, with reload=False available when a group of files should be reloaded once at the end. link_state reconciles a link's kernel up flag with networkctl up/down, reporting a change only when the flag differs, and refusing to guess about an interface the host does not report. reload and reconfigure_links are stateless remediation: they read no fact, always report a change and always yield their command, because "these links already have these files" is not cheap to observe. Removing a unit is the same write with present=False: one rm -f, the same reload chaining, the same read-back gate.
Three boundaries matter when composing it. The module does not own the daemon: systemd-networkd.service is an ordinary unit, so enabling and starting it belongs to the systemd module. The module never touches a competing manager: stopping NetworkManager on a live host can re-address the interface carrying your session, and that decision stays yours to make explicitly. And if what you actually want to edit is the host's netplan YAML, the netplan module is the right tool — this one exists for the units you write yourself.
Managing network services from Python
A playbook that manages these units has a fixed shape: render a template, notify a handler, ensure the daemon, gather state afterwards. Each piece has a direct counterpart in a Reemote deploy:
- Writing a finished unit from a string:
op(systemd_networkd.network_unit, filename=..., content=..., sudo=True). - Building that text from a table of options instead of a template file: an ordinary Python function, then the same request.
- Managing a group of units in one deploy: a loop yielding one request per file,
reload=Falseon all but the last. - The "notify the reload handler" step: the chained reload, which fires only if the bytes actually changed.
- Removing a unit: the same request with
present=False. - Enabling the daemon itself:
op(systemd.service, service="systemd-networkd", running=True, enabled=True, sudo=True). - Bringing a link up, re-reading units, renewing a lease:
link_state,reload,reconfigure_links(renew=True). - Reading what a host holds: the four facts, with
gather_factacross the fleet. - Skipping hosts of another family:
when=is_ubuntuon the request. - Checking what would change before touching the network: that is what the
dry=Truephase of every run already is.
Two conventions carry through every example below. Arguments passed to op() must stay hashable, so tables are tuples of tuples and unit bodies are plain strings; and the escalation flag belongs to the request (sudo=True) while the run-as user stays a property of the inventory. The when=is_ubuntu guard means a mixed fleet skips non-Ubuntu hosts instead of failing on them.
Inventory for the systemd_networkd host
The examples use the repository's real Ubuntu SSH host. Save an equivalent inventory as inventory.json:
[
{
"host": "ubuntu",
"family": "Ubuntu",
"connection": {
"connector": "ssh",
"address": "192.168.0.251",
"port": 22,
"username": "supervisor",
"key_path": "~/.ssh/id_ed25519"
},
"tags": ["ubuntu_host", "apt_package_manager"]
}
]
Replace the address, user and key path with your own. Every managed write lands under /etc/systemd/network, so the login needs passwordless sudo; verify the host key and populate ~/.ssh/known_hosts rather than disabling host-key checking, as the SSH connector reference describes. Look at what the host already has before you start, because the generated units under /run tell you which links networkd already claims:
ssh supervisor@192.168.0.251 'ls -l /etc/systemd/network; networkctl list'
Runnable examples for the inventory Ubuntu host
Clone the repository and edit its inventory.json, or replace that file with the inventory above:
git clone https://github.com/kimjarvis/reemote.git
cd reemote
The scripts under examples/articles/systemd_networkd/ load that inventory, select only entries whose family is Ubuntu, and use sudo for the root-owned state. Mutating scripts preview by default and require --apply; the inspection script is read-only. They share one helper, systemd_networkd_article_common.py, which holds the managed-unit list and the preview/apply driver.
| Example | Article concept |
|---|---|
systemd_networkd_hello.py |
The canonical two operations against persistent SSH hosts |
systemd_networkd_service.py |
Keep the daemon running and enabled with the systemd module |
systemd_networkd_static.py |
One static IPv4 .network unit with a chained reload |
systemd_networkd_rendered.py |
Render units from a Python table instead of a template |
systemd_networkd_dhcp.py |
DHCP lease behaviour, plus a .link file no reload reads |
systemd_networkd_bond.py |
A bond, a VLAN and a bridge across .netdev and .network pairs |
systemd_networkd_inspect.py |
Read back units, links and configuration; --check gate |
systemd_networkd_activate.py |
link_state, reload and lease renewal on a live link |
systemd_networkd_cleanup.py |
Remove every unit the article manages |
Every example names interfaces the lab host does not have — eth1 through eth4, lab0, lab1, lan99 — and every virtual device it creates (rmbond0, rmvlan110, rmbr0) comes up with no members and no route to anywhere, so the files can be applied repeatedly on a machine you are logged into, and the cleanup script takes the whole set back down again. The only example that acts on a live link is systemd_networkd_activate.py, and its default interface is lo. Point a [Match] at a real interface only on a host you can reach out of band.
Run a read-only preview from the repository root:
uv run python examples/articles/systemd_networkd/systemd_networkd_static.py
Run the canonical pair on a real host
The first script is the quickstart's two files.install operations, kept as the article's baseline against a persistent host: same requests, same preview-then-apply shape, SSH instead of a container, and a family guard so a RedHat host in the same inventory is skipped rather than failing.
# systemd_networkd_hello.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Run the canonical two operations against persistent Ubuntu SSH hosts."""
import asyncio
import sys
from pathlib import Path
from reemote import files, op
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
execute,
is_ubuntu,
load_inventory,
parser,
)
def deploy(host):
yield op(
files.install,
name="Write a greeting",
content="Hello from reemote!\n",
dest="/tmp/reemote-hello.txt",
mode="0644",
when=is_ubuntu,
)
yield op(
files.install,
name="Record the host name",
content=f"written on {host.name}\n",
dest="/tmp/reemote-host.txt",
mode="0644",
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The preview reads the host and reports what it would write, without sending a mutating command:
== Preview ==
ubuntu: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install]
ubuntu: Record the host name [changed: content /tmp/reemote-host.txt is absent, will install]
Preview only; pass --apply to change the hosts.
Keep the daemon running and enabled
A playbook that manages .network units starts by making sure the daemon that reads them is actually up. Reemote deliberately does not wrap that work inside systemd_networkd — systemd-networkd.service is an ordinary unit, and the systemd module already owns it — so this example is two plain service requests: the daemon running and enabled, and the oneshot boot waiter enabled without any claim about its running state (running=None, because a oneshot unit is never "running" the way a daemon is).
# systemd_networkd_service.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Keep the networkd daemon itself running and enabled with ``systemd.service``.
A playbook that manages ``.network`` units starts by making sure the daemon
that reads them is actually up, and stops whichever competing manager the
distribution shipped. Reemote deliberately does not wrap that work inside
``systemd_networkd``: ``systemd-networkd.service`` is an ordinary systemd unit,
so the ``systemd`` module already owns it, and re-wrapping
``enabled``/``running`` under a second name would only hide that.
The example asks for two things:
* ``systemd-networkd.service`` running and enabled at boot — the daemon that
reads ``/etc/systemd/network`` and answers ``networkctl``;
* ``systemd-networkd-wait-online.service`` enabled only
(``running=None``): it is a oneshot boot waiter, so it is never "running"
the way a daemon is, and managing its boot membership is the whole job.
Both requests are idempotent reads of ``SystemdServiceState`` /
``SystemdServiceEnabled``: on a converged host each reports ``no change`` and
sends nothing.
**The example never touches NetworkManager.** A host that renders its
networking with NetworkManager is not a host to hand over to networkd from an
SSH session — stopping the current manager can re-address the interface
carrying the session. The lab hosts here already run networkd (Ubuntu server
renders with netplan's networkd backend), so this script only proves the
daemon is up before the unit-file examples run.
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
execute,
is_ubuntu,
load_inventory,
parser,
)
def deploy(host):
yield op(
systemd.service,
name="Run systemd-networkd",
service="systemd-networkd",
running=True,
enabled=True,
sudo=True,
when=is_ubuntu,
)
yield op(
systemd.service,
name="Enable the boot wait-online unit",
service="systemd-networkd-wait-online",
running=None,
enabled=True,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The apply shows the commands the two requests expand into — one start and two enable calls:
== Applied ==
ubuntu: Run systemd-networkd [changed: systemd-networkd.service not running (None), will start; systemd-networkd.service not enabled, will enable]
$ sudo systemctl start systemd-networkd.service
$ sudo systemctl enable systemd-networkd.service
ubuntu: Enable the boot wait-online unit [changed: systemd-networkd-wait-online.service active state left alone; systemd-networkd-wait-online.service not enabled, will enable]
$ sudo systemctl enable systemd-networkd-wait-online.service
A second pass reads the same two facts and sends nothing:
== Applied ==
ubuntu: Run systemd-networkd [no change: systemd-networkd.service already running; systemd-networkd.service already enabled]
ubuntu: Enable the boot wait-online unit [no change: systemd-networkd-wait-online.service active state left alone; systemd-networkd-wait-online.service already enabled]
The example never touches NetworkManager, and neither should you from an SSH session: a host that renders its networking with NetworkManager is a host where stopping the current manager can re-address the interface carrying your connection. The lab host already runs networkd, so this script only proves the daemon is up before the unit-file examples run.
Write one static IPv4 unit
One network_unit request is the whole static-IP story: a complete INI document for a named unit file. The operation compares that text byte for byte against the NetworkdUnitFile read-back — the trailing newline is part of the contract — so the template file, the handler and the "restart if changed" notification collapse into a single request, and the reload that follows in the transcript below is there only because the bytes actually changed.
# systemd_networkd_static.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Write one static-IPv4 ``.network`` unit with ``systemd_networkd.network_unit``.
The example manages ``/etc/systemd/network/60-reemote-eth1.network``: a whole
INI document handed to the operation as a plain string. ``network_unit`` reads
the file back through ``NetworkdUnitFile`` and compares **byte for byte** — the
trailing newline is part of the contract — so a template file, a handler and a
"restart if changed" notification all collapse into one request: the reload is
*chained by the operation itself*, and only on a real change.
The unit gives an interface a static address, a gateway, two resolvers and a
search domain — the same content a Jinja ``10-eth0.network.j2`` template would
render::
[Match]
Name=eth1
[Network]
Address=10.30.0.11/24
Gateway=10.30.0.1
DNS=1.1.1.1
DNS=9.9.9.9
Domains=lab.example
**Nothing here touches the interface carrying the session.** The ``[Match]``
names ``eth1``, which the lab host does not have, so the chained ``networkctl
reload`` re-reads every unit file — including netplan's rendered copies under
``/run/systemd/network`` — and reconfigures no live link. Point a ``Name=`` at
a real interface only on a machine you can reach out of band: changing the
address or default route of the link carrying your SSH session drops it.
Run it with::
uv run python examples/articles/systemd_networkd/systemd_networkd_static.py
uv run python examples/articles/systemd_networkd/systemd_networkd_static.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
STATIC_UNIT,
execute,
is_ubuntu,
load_inventory,
parser,
)
STATIC_CONTENT = (
"# Managed by Reemote. Do not edit by hand.\n"
"[Match]\n"
"Name=eth1\n"
"\n"
"[Network]\n"
"Address=10.30.0.11/24\n"
"Gateway=10.30.0.1\n"
"DNS=1.1.1.1\n"
"DNS=9.9.9.9\n"
"Domains=lab.example\n"
"\n"
"[Link]\n"
"MTUBytes=9000\n"
)
def deploy(host):
yield op(
systemd_networkd.network_unit,
name="Configure a static IPv4 address on eth1",
filename=STATIC_UNIT,
content=STATIC_CONTENT,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The content is what a template would have rendered:
# Managed by Reemote. Do not edit by hand.
[Match]
Name=eth1
[Network]
Address=10.30.0.11/24
Gateway=10.30.0.1
DNS=1.1.1.1
DNS=9.9.9.9
Domains=lab.example
[Link]
MTUBytes=9000
Review the plan, then apply it. The preview names the file and the reason it collected:
== Preview ==
ubuntu: Configure a static IPv4 address on eth1 [changed: networkd unit /etc/systemd/network/60-reemote-eth1.network missing or differs from the content]
Preview only; pass --apply to change the hosts.
The apply shows the three commands the request expanded into — an unprivileged spool transfer, one elevated shell step that installs the file with its mode and deletes the spool, and the chained reload:
== Applied ==
ubuntu: Configure a static IPv4 address on eth1 [changed: networkd unit /etc/systemd/network/60-reemote-eth1.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-14cd242c9cd2276d/60-reemote-eth1.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-14cd242c9cd2276d/60-reemote-eth1.network /etc/systemd/network/60-reemote-eth1.network && chmod 0644 /etc/systemd/network/60-reemote-eth1.network && rm -rf /tmp/reemote-systemd-networkd-14cd242c9cd2276d'
$ sudo networkctl reload
Running the same script again sends nothing. network_unit compares the wanted text against what NetworkdUnitFile reads back, so an unchanged file is not rewritten, not re-uploaded — and not reloaded either, because the reload is chained to the write:
== Preview ==
ubuntu: Configure a static IPv4 address on eth1 [no change: networkd unit already up to date (/etc/systemd/network/60-reemote-eth1.network)]
Preview only; pass --apply to change the hosts.
That is the whole convergence story of the write family: the second pass reports no change and issues no commands, and the installed file ends up root:root mode 0644, the ownership networkd expects. The unit itself carries the same addressing a hand-written template would: a static address, a gateway, two resolvers and a search domain in [Network], an MTU in [Link] — and a [Match] naming eth1, which the lab host does not have, so the chained reload reconfigures no live link.
Render units on the control side
A template file cannot survive contact with this model: network_unit takes finished text, so the loop, the conditionals and the section layout live on the control side, in ordinary Python. The next example keeps each unit in a table of tuples — one row per file, each a bare filename and a tuple of (section, options) pairs — and builds the documents from it, including the repeated keys an INI file spells as ordinary repeats: two Address= rows, two DNS= servers.
# systemd_networkd_rendered.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Render ``.network`` units on the control side instead of templating them.
A playbook ships one Jinja template plus a list of dictionaries and lets the
target render them together. Reemote has no template operation:
``network_unit`` takes the finished file text, so the rendering is an ordinary
Python function that runs where the deploy runs. The table below is the data a
template variable would have held — one row per unit, each a bare filename and
a tuple of ``(section, options)`` pairs — and ``render_unit`` turns a row into
the exact bytes the file will contain, including the header comment and the
trailing newline.
Because the render is a pure function of module-level constants, the text is
identical in the preview and the apply, which is what the determinism guard
insists on, and the same function a reader can unit-test without a host.
The group is written with ``reload=False`` on every request but the last, so
one ``networkctl reload`` follows the whole batch instead of one per file:
the reload re-reads *every* unit in the directory, so a final reload costs the
same as a reload per file and also picks up a broken sibling the moment it is
fixed. Both units ``[Match]`` absent lab devices, so nothing here changes the
running network even after an apply.
Run it with::
uv run python examples/articles/systemd_networkd/systemd_networkd_rendered.py
uv run python examples/articles/systemd_networkd/systemd_networkd_rendered.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
LAB_UNITS,
execute,
is_ubuntu,
load_inventory,
parser,
)
# One row per unit: ``(filename, sections)`` with ``sections`` a tuple of
# ``(section_name, options)`` and ``options`` a tuple of ``(key, value)``
# string pairs. Repeated keys (two ``Address=`` rows, several ``DNS=``) are
# ordinary repeats, exactly as the INI file spells them.
LAB_TABLE = (
(
LAB_UNITS[0],
(
("Match", (("Name", "lab0"),)),
(
"Network",
(
("Address", "10.30.10.11/24"),
("Address", "10.30.10.12/24"),
("Gateway", "10.30.10.1"),
("DNS", "1.1.1.1"),
("DNS", "9.9.9.9"),
),
),
("Link", (("MTUBytes", "9000"),)),
),
),
(
LAB_UNITS[1],
(
("Match", (("Name", "lab1"), ("Type", "ether"),)),
(
"Network",
(
("Address", "10.30.20.11/24"),
("Domains", "lab.example"),
),
),
("Route", (("Destination", "10.31.0.0/24"), ("Gateway", "10.30.20.1"),)),
),
),
)
HEADER = "# Managed by Reemote. Rendered on the control side.\n"
def render_unit(sections):
"""Build one whole unit file's text from ``(section, options)`` pairs."""
rows = [HEADER]
for name, options in sections:
rows.append(f"[{name}]\n")
rows.extend(f"{key}={value}\n" for key, value in options)
rows.append("\n")
return "".join(rows).rstrip("\n") + "\n"
LAB_DOCUMENTS = tuple(
(filename, render_unit(sections)) for filename, sections in LAB_TABLE
)
def deploy(host):
last = len(LAB_DOCUMENTS) - 1
for index, (filename, content) in enumerate(LAB_DOCUMENTS):
yield op(
systemd_networkd.network_unit,
name=f"Render {filename}",
filename=filename,
content=content,
reload=index == last,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The render is a pure function of module-level constants, so the preview and the apply agree byte for byte — which is what the determinism guard insists on — and the same function a reader can unit-test without a host. For the first table row it produces:
# Managed by Reemote. Rendered on the control side.
[Match]
Name=lab0
[Network]
Address=10.30.10.11/24
Address=10.30.10.12/24
Gateway=10.30.10.1
DNS=1.1.1.1
DNS=9.9.9.9
[Link]
MTUBytes=9000
The group shows the batch economy: every request but the last is written with reload=False, so one networkctl reload follows the whole batch instead of one per file, because the reload re-reads every unit in the directory anyway and costs the same either way. The preview shows the asymmetry — neither write mentions a reload yet:
== Preview ==
ubuntu: Render 60-reemote-lab0.network [changed: networkd unit /etc/systemd/network/60-reemote-lab0.network missing or differs from the content]
ubuntu: Render 60-reemote-lab1.network [changed: networkd unit /etc/systemd/network/60-reemote-lab1.network missing or differs from the content]
Preview only; pass --apply to change the hosts.
and the applied log carries exactly one reload line, after the final install:
== Applied ==
ubuntu: Render 60-reemote-lab0.network [changed: networkd unit /etc/systemd/network/60-reemote-lab0.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-ced28f1f9ad5070f/60-reemote-lab0.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-ced28f1f9ad5070f/60-reemote-lab0.network /etc/systemd/network/60-reemote-lab0.network && chmod 0644 /etc/systemd/network/60-reemote-lab0.network && rm -rf /tmp/reemote-systemd-networkd-ced28f1f9ad5070f'
ubuntu: Render 60-reemote-lab1.network [changed: networkd unit /etc/systemd/network/60-reemote-lab1.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-087690a5963ab0c6/60-reemote-lab1.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-087690a5963ab0c6/60-reemote-lab1.network /etc/systemd/network/60-reemote-lab1.network && chmod 0644 /etc/systemd/network/60-reemote-lab1.network && rm -rf /tmp/reemote-systemd-networkd-087690a5963ab0c6'
$ sudo networkctl reload
lab1's row also demonstrates the two [Match] keys worth knowing: Name= matches the interface name (a shell-style pattern, so Name=eth* claims every eth device), and Type=ether narrows the match to real Ethernet links so the unit skips the bonds and VLANs it would otherwise enslave itself into.
Keep a DHCP link predictable, and stage a .link file
Static addressing is only half of a real host. A link that stays on DHCP still needs its lease behaviour pinned down — which of the server's offers the daemon may apply, and at what cost — and the device itself may need renaming before any .network can match it. This example manages one of each kind in a single deploy:
# systemd_networkd_dhcp.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Keep a link on DHCP with explicit lease behaviour, and stage a ``.link`` file.
Two unit kinds, one deploy:
* ``60-reemote-dhcp-eth2.network`` leaves the link on DHCP but pins down what
the lease is allowed to do: ``UseDNS``/``UseNTP``/``UseRoutes`` name the
lease options the daemon may apply, ``RouteMetric`` orders the default route
against the other links, and ``SendHostname`` controls the option the
server sees. ``IPv6AcceptRA=no`` mutes router discovery on a link that
should answer only through its lease.
* ``90-reemote-lan99.link`` is a *device* file, and the teaching case: it
shares ``/etc/systemd/network`` but belongs to **systemd-udevd**, not to
networkd. It renames the device that appears on the given PCI path and sets
its MAC and MTU before any ``.network`` can match the new name. Because
``networkctl reload`` does not re-read ``.link`` files, ``network_unit``
never chains one for this kind — the write converges like any other, but
udev applies it on the next event for that device (``udevadm test`` is how
you inspect that, outside reemote).
Both names are absent on the lab host — no ``eth2``, nothing on that PCI
path — so the pair is inert until it matches a real device on a machine you
can reach out of band.
Run it with::
uv run python examples/articles/systemd_networkd/systemd_networkd_dhcp.py
uv run python examples/articles/systemd_networkd/systemd_networkd_dhcp.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
DHCP_UNITS,
execute,
is_ubuntu,
load_inventory,
parser,
)
DHCP_CONTENT = (
"# Managed by Reemote. Do not edit by hand.\n"
"[Match]\n"
"Name=eth2\n"
"\n"
"[Network]\n"
"DHCP=yes\n"
"IPv6AcceptRA=no\n"
"\n"
"[DHCPv4]\n"
"UseDNS=yes\n"
"UseNTP=yes\n"
"UseRoutes=yes\n"
"UseMTU=yes\n"
"RouteMetric=100\n"
"SendHostname=yes\n"
"ClientIdentifier=mac\n"
)
LINK_CONTENT = (
"# Managed by Reemote. Applied by systemd-udevd, not by networkctl reload.\n"
"[Match]\n"
"Path=pci-0000:00:03.0\n"
"\n"
"[Link]\n"
"Name=lan99\n"
"MACAddress=02:42:ac:11:00:99\n"
"MTUBytes=9000\n"
"AutoNegotiation=yes\n"
)
def deploy(host):
yield op(
systemd_networkd.network_unit,
name=f"Write {DHCP_UNITS[0]}",
filename=DHCP_UNITS[0],
content=DHCP_CONTENT,
sudo=True,
when=is_ubuntu,
)
# A .link write chains no reload: the daemon never reads these files, so
# the operation deliberately yields only the write for this unit.
yield op(
systemd_networkd.network_unit,
name=f"Write {DHCP_UNITS[1]}",
filename=DHCP_UNITS[1],
content=LINK_CONTENT,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The .network leaves the link on DHCP but names what the lease is allowed to do: UseDNS, UseNTP and UseRoutes pick the lease options the daemon may apply, RouteMetric orders the default route against the other links, SendHostname controls the option the server sees, and IPv6AcceptRA=no mutes router discovery on a link that should answer only through its lease. The .link is the teaching case: it shares /etc/systemd/network but belongs to systemd-udevd, renames whatever device appears on the given PCI path, and sets its MAC and MTU before any .network sees the new name.
The applied log carries the module's kind-awareness. The .network write chains networkctl reload; the .link write chains nothing at all, because the daemon never re-reads .link files — udevd applies one on the next event for that device. Converging the file is the operation's job; pretending a reload would activate it is not:
== Applied ==
ubuntu: Write 60-reemote-dhcp-eth2.network [changed: networkd unit /etc/systemd/network/60-reemote-dhcp-eth2.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-4f33e14fdd0aff39/60-reemote-dhcp-eth2.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-4f33e14fdd0aff39/60-reemote-dhcp-eth2.network /etc/systemd/network/60-reemote-dhcp-eth2.network && chmod 0644 /etc/systemd/network/60-reemote-dhcp-eth2.network && rm -rf /tmp/reemote-systemd-networkd-4f33e14fdd0aff39'
$ sudo networkctl reload
ubuntu: Write 90-reemote-lan99.link [changed: networkd unit /etc/systemd/network/90-reemote-lan99.link missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-6ebca0845e160cf5/90-reemote-lan99.link
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-6ebca0845e160cf5/90-reemote-lan99.link /etc/systemd/network/90-reemote-lan99.link && chmod 0644 /etc/systemd/network/90-reemote-lan99.link && rm -rf /tmp/reemote-systemd-networkd-6ebca0845e160cf5'
Both names are absent on the lab host — there is no eth2, and nothing on that PCI path — so the pair sits inert in the directory, visible to NetworkdUnits and matched by no link, until it lands on a machine that has the device.
Layer a bond, a VLAN and a bridge
Virtual devices in systemd-networkd are declared in two places at once, and a configuration that gets only one half right silently does nothing: the .netdev file creates the device, and a .network file enslaves and addresses it — a member carries Bond=/Bridge=/VLAN= in its [Network], and the device that should hold an address matches its own name. This example lays a whole tree a layered host uses, in one deploy:
eth3 + eth4 -> rmbond0 (802.3ad) -> rmvlan110 (VLAN 110) -> rmbr0
# systemd_networkd_bond.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Layer a bond, a VLAN and a bridge with ``.netdev`` and ``.network`` units.
Virtual devices in systemd-networkd are declared in two places at once, and a
deployment that gets one half right silently does nothing:
* a ``.netdev`` file *creates* the device — ``[NetDev] Kind=bond`` (or
``vlan``, ``bridge``) plus the kind's own section (``[Bond]``, ``[VLAN]``,
``[Bridge]``);
* a ``.network`` file *enslaves and addresses* it — a member carries
``Bond=``/``Bridge=``/``VLAN=`` in ``[Network]``, and the device that should
hold an address matches its own name.
The example lays the whole tree a layered infrastructure host uses, in one
deploy:
``eth3 + eth4 -> rmbond0 (802.3ad) -> rmvlan110 (VLAN 110) -> rmbr0``
The bond carries no address (the bridge is addressed instead), the VLAN is
listed on its parent's ``VLAN=`` and enslaved via ``Bridge=``, and the bridge
holds the management address plus one static route spelled as a ``[Route]``
section — the file-level counterpart of the free-form overrides a role's
config dictionary would need.
Every unit rides in a tuple of ``(filename, content)`` pairs; the loop writes
them all with ``reload=False`` but the last, so one chained ``networkctl
reload`` creates the netdevs and reconfigures the matching links at the end.
None of the member interfaces exists on the lab host, so the bond has no
slaves and the tree carries no traffic — but the three virtual links do come
up after the reload, which is exactly what removal takes back down.
Run it with::
uv run python examples/articles/systemd_networkd/systemd_networkd_bond.py
uv run python examples/articles/systemd_networkd/systemd_networkd_bond.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
BOND_UNITS,
execute,
is_ubuntu,
load_inventory,
parser,
)
# (filename, content) in creation order: netdevs first, then the members,
# then each enslaved/addressed device. networkd reads every file regardless of
# order, but this is the order a reader follows.
BOND_TREE = (
(
BOND_UNITS[0],
"[NetDev]\nName=rmbond0\nKind=bond\n\n[Bond]\nMode=802.3ad\n"
"TransmitHashPolicy=layer3+4\nLACPTransmitRate=fast\nMIIMonitorSec=1s\n",
),
(
BOND_UNITS[1],
"[NetDev]\nName=rmvlan110\nKind=vlan\n\n[VLAN]\nId=110\n",
),
(
BOND_UNITS[2],
"[NetDev]\nName=rmbr0\nKind=bridge\n\n[Bridge]\nForwardDelay=15\n"
"HelloTime=2\nMaxAge=20\n",
),
(
BOND_UNITS[3],
"[Match]\nName=eth3\n\n[Network]\nBond=rmbond0\n\n"
"[Link]\nMTUBytes=9000\n",
),
(
BOND_UNITS[4],
"[Match]\nName=eth4\n\n[Network]\nBond=rmbond0\n\n"
"[Link]\nMTUBytes=9000\n",
),
(
BOND_UNITS[5],
"[Match]\nName=rmbond0\n\n[Network]\nVLAN=rmvlan110\n\n"
"[Link]\nMTUBytes=9000\n",
),
(
BOND_UNITS[6],
"[Match]\nName=rmvlan110\n\n[Network]\nBridge=rmbr0\n\n"
"[Link]\nMTUBytes=9000\n",
),
(
BOND_UNITS[7],
"[Match]\nName=rmbr0\n\n[Network]\nAddress=172.30.110.10/24\n"
"DNS=1.1.1.1\n\n[Route]\nDestination=10.100.0.0/16\n"
"Gateway=172.30.110.1\n",
),
)
def deploy(host):
last = len(BOND_TREE) - 1
for index, (filename, content) in enumerate(BOND_TREE):
yield op(
systemd_networkd.network_unit,
name=f"Write {filename}",
filename=filename,
content=content,
reload=index == last,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
Three .netdev files create rmbond0 (802.3ad, layer-3+4 hashing, fast LACP), rmvlan110 (tag 110) and rmbr0 (a bridge with explicit timer settings); two member .network files enslave eth3 and eth4; rmbond0 itself carries no address and merely lists its VLAN; the VLAN is enslaved by the bridge; and the bridge holds the management address plus a static route spelled as a [Route] section — the file-level counterpart of the free-form overrides a role's config dictionary would need. The eight writes ride in one tuple, ordered the way a reader follows the tree, and only the last chains the reload:
== Applied ==
ubuntu: Write 61-reemote-rmbond0.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmbond0.netdev missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-4d84ae2891e75fe9/61-reemote-rmbond0.netdev
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-4d84ae2891e75fe9/61-reemote-rmbond0.netdev /etc/systemd/network/61-reemote-rmbond0.netdev && chmod 0644 /etc/systemd/network/61-reemote-rmbond0.netdev && rm -rf /tmp/reemote-systemd-networkd-4d84ae2891e75fe9'
ubuntu: Write 61-reemote-rmvlan110.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmvlan110.netdev missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-6c1acb864d9eedeb/61-reemote-rmvlan110.netdev
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-6c1acb864d9eedeb/61-reemote-rmvlan110.netdev /etc/systemd/network/61-reemote-rmvlan110.netdev && chmod 0644 /etc/systemd/network/61-reemote-rmvlan110.netdev && rm -rf /tmp/reemote-systemd-networkd-6c1acb864d9eedeb'
ubuntu: Write 61-reemote-rmbr0.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmbr0.netdev missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-4abfd8d685bca185/61-reemote-rmbr0.netdev
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-4abfd8d685bca185/61-reemote-rmbr0.netdev /etc/systemd/network/61-reemote-rmbr0.netdev && chmod 0644 /etc/systemd/network/61-reemote-rmbr0.netdev && rm -rf /tmp/reemote-systemd-networkd-4abfd8d685bca185'
ubuntu: Write 62-reemote-eth3.network [changed: networkd unit /etc/systemd/network/62-reemote-eth3.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-4f3f37dc8fe1d385/62-reemote-eth3.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-4f3f37dc8fe1d385/62-reemote-eth3.network /etc/systemd/network/62-reemote-eth3.network && chmod 0644 /etc/systemd/network/62-reemote-eth3.network && rm -rf /tmp/reemote-systemd-networkd-4f3f37dc8fe1d385'
ubuntu: Write 62-reemote-eth4.network [changed: networkd unit /etc/systemd/network/62-reemote-eth4.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-efd9c6269457d832/62-reemote-eth4.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-efd9c6269457d832/62-reemote-eth4.network /etc/systemd/network/62-reemote-eth4.network && chmod 0644 /etc/systemd/network/62-reemote-eth4.network && rm -rf /tmp/reemote-systemd-networkd-efd9c6269457d832'
ubuntu: Write 63-reemote-rmbond0.network [changed: networkd unit /etc/systemd/network/63-reemote-rmbond0.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-f0adfa06b4f590e0/63-reemote-rmbond0.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-f0adfa06b4f590e0/63-reemote-rmbond0.network /etc/systemd/network/63-reemote-rmbond0.network && chmod 0644 /etc/systemd/network/63-reemote-rmbond0.network && rm -rf /tmp/reemote-systemd-networkd-f0adfa06b4f590e0'
ubuntu: Write 63-reemote-rmvlan110.network [changed: networkd unit /etc/systemd/network/63-reemote-rmvlan110.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-7e708684981ab639/63-reemote-rmvlan110.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-7e708684981ab639/63-reemote-rmvlan110.network /etc/systemd/network/63-reemote-rmvlan110.network && chmod 0644 /etc/systemd/network/63-reemote-rmvlan110.network && rm -rf /tmp/reemote-systemd-networkd-7e708684981ab639'
ubuntu: Write 63-reemote-rmbr0.network [changed: networkd unit /etc/systemd/network/63-reemote-rmbr0.network missing or differs from the content]
$ scp <networkd unit> -> /tmp/reemote-systemd-networkd-5135376f1b2506b9/63-reemote-rmbr0.network
$ sudo sh -c 'mkdir -p /etc/systemd/network && cp /tmp/reemote-systemd-networkd-5135376f1b2506b9/63-reemote-rmbr0.network /etc/systemd/network/63-reemote-rmbr0.network && chmod 0644 /etc/systemd/network/63-reemote-rmbr0.network && rm -rf /tmp/reemote-systemd-networkd-5135376f1b2506b9'
$ sudo networkctl reload
None of eth3/eth4 exists on the lab host, so the bond has no slaves and the tree carries no traffic — but on a real machine the single chained networkctl reload is the moment all three virtual links spring into existence, which is exactly what removal takes back down.
Inspect the result
Four facts cover what is worth knowing about a host, and this script gathers all of them across the inventory in concurrent round trips. It mutates nothing, and its --check flag turns the same read into a gate that exits nonzero until every unit the article manages exists.
# systemd_networkd_inspect.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Read back what systemd-networkd actually holds, using the four networkd facts.
This script mutates nothing. It gathers the four facts the ``systemd_networkd``
module offers:
* ``NetworkdUnits`` — every unit file under ``/etc/systemd/network`` as
filename -> ``kind``/``path``/``mode``, one shell round trip;
* ``NetworkdUnitFile`` — the raw text of one named file, so each managed unit
can be checked for presence without parsing anything;
* ``NetworkdLinks`` — ``networkctl list --json=short`` projected per interface:
the administrative and operational states, the kernel ``up`` flag, the MAC,
the addresses in CIDR form and the ``.network`` file the link matched (which
for a netplan-rendered host lives under ``/run/systemd/network`` — the
volatile directory the fact deliberately does not manage);
* ``NetworkdConfig`` — the effective ``networkd.conf`` plus drop-in settings
flattened to ``Section.Key``; an untouched host reads ``{}`` because the
stock file comments every row.
None of the reads needs elevation, and each ``gather_fact`` fans out across the
hosts concurrently. Pass ``--check`` to exit nonzero until every unit this
article manages is present.
"""
import asyncio
import sys
import textwrap
from pathlib import Path
from reemote import (
Host,
NetworkdConfig,
NetworkdLinks,
NetworkdUnitFile,
NetworkdUnits,
gather_fact,
)
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
MANAGED_PATHS,
MANAGED_UNITS,
NETWORK_DIR,
load_inventory,
parser,
)
async def collect(hosts):
"""Gather the four fact groups across the hosts and align them per host."""
units = await gather_fact(hosts, NetworkdUnits)
links = await gather_fact(hosts, NetworkdLinks)
config = await gather_fact(hosts, NetworkdConfig)
managed = {}
for name, path in zip(MANAGED_UNITS, MANAGED_PATHS):
texts = await gather_fact(hosts, NetworkdUnitFile, path)
managed[name] = {host: text is not None for host, text in texts.items()}
rows = {}
for host in hosts:
rows[host.name] = {
"units": units[host.name],
"links": links[host.name],
"config": config[host.name],
"managed": {name: flags[host.name] for name, flags in managed.items()},
}
return rows
def managed_are_present(rows):
"""Whether every managed unit exists on every host."""
return all(all(row["managed"].values()) for row in rows.values())
async def main(argv=None):
cli = parser(__doc__, mutating=False)
cli.add_argument(
"--check",
action="store_true",
help="exit nonzero until every managed unit is present",
)
args = cli.parse_args(argv)
inventory = load_inventory(args.inventory)
hosts = [Host.from_inventory(entry) for entry in inventory]
try:
rows = await collect(hosts)
finally:
await asyncio.gather(*(host.aclose() for host in hosts))
for name, row in rows.items():
print(f"== {name} ==")
if not row["units"]:
print("units: (no admin-owned files under /etc/systemd/network)")
else:
print("units:")
for unit, info in row["units"].items():
kind = "managed" if unit in MANAGED_UNITS else "unmanaged"
print(f" {info['path']} [{kind}, mode {info['mode']}]")
print("managed units:")
for unit, present in row["managed"].items():
print(f" {NETWORK_DIR}/{unit}: {'present' if present else 'absent'}")
print("links known to networkctl:")
for link, info in sorted(row["links"].items()):
state = info["administrative_state"] or "?"
flag = "up" if info["up"] else "down"
matched = info["network_file"] or "(no unit matched)"
print(f" {link}: {state}, {flag}, {matched}")
print("manager configuration:")
if not row["config"]:
print(" (default: every row commented out)")
for key, value in sorted(row["config"].items()):
print(textwrap.indent(f"{key} = {value}", " "))
if args.check:
if not managed_are_present(rows):
incomplete = [
name for name, row in rows.items() if not all(row["managed"].values())
]
print(f"incomplete on: {', '.join(incomplete)}")
raise SystemExit(1)
print("every managed unit is present")
return rows
if __name__ == "__main__":
asyncio.run(main())
With the examples above applied, the listing shows the thirteen managed units grouped by kind — nine .network files, three .netdev, one .link — the lo loopback as the only link networkctl reports, unmanaged and up, and a manager configuration that is empty because every row of the stock networkd.conf is commented out:
== ubuntu ==
units:
/etc/systemd/network/60-reemote-dhcp-eth2.network [managed, mode 644]
/etc/systemd/network/60-reemote-eth1.network [managed, mode 644]
/etc/systemd/network/60-reemote-lab0.network [managed, mode 644]
/etc/systemd/network/60-reemote-lab1.network [managed, mode 644]
/etc/systemd/network/62-reemote-eth3.network [managed, mode 644]
/etc/systemd/network/62-reemote-eth4.network [managed, mode 644]
/etc/systemd/network/63-reemote-rmbond0.network [managed, mode 644]
/etc/systemd/network/63-reemote-rmbr0.network [managed, mode 644]
/etc/systemd/network/63-reemote-rmvlan110.network [managed, mode 644]
/etc/systemd/network/61-reemote-rmbond0.netdev [managed, mode 644]
/etc/systemd/network/61-reemote-rmbr0.netdev [managed, mode 644]
/etc/systemd/network/61-reemote-rmvlan110.netdev [managed, mode 644]
/etc/systemd/network/90-reemote-lan99.link [managed, mode 644]
managed units:
/etc/systemd/network/60-reemote-eth1.network: present
/etc/systemd/network/60-reemote-lab0.network: present
/etc/systemd/network/60-reemote-lab1.network: present
/etc/systemd/network/60-reemote-dhcp-eth2.network: present
/etc/systemd/network/90-reemote-lan99.link: present
/etc/systemd/network/61-reemote-rmbond0.netdev: present
/etc/systemd/network/61-reemote-rmvlan110.netdev: present
/etc/systemd/network/61-reemote-rmbr0.netdev: present
/etc/systemd/network/62-reemote-eth3.network: present
/etc/systemd/network/62-reemote-eth4.network: present
/etc/systemd/network/63-reemote-rmbond0.network: present
/etc/systemd/network/63-reemote-rmvlan110.network: present
/etc/systemd/network/63-reemote-rmbr0.network: present
links known to networkctl:
lo: unmanaged, up, (no unit matched)
manager configuration:
(default: every row commented out)
every managed unit is present
Before the first example ran, the same command listed no units and --check reported incomplete on: ubuntu with exit status 1 — the shape you want in a pipeline that must not proceed against a half-configured host. NetworkdLinks is the fact to watch after a real change: its network_file column names the unit each link actually matched, whether that file lives in /etc/systemd/network or in netplan's rendered /run/systemd/network.
Drive the running daemon
Everything so far went through files, with a reload chained to the writes that needed one. This example stands apart: it commands the running daemon directly — link_state to reconcile a link's kernel up flag, then reload or reconfigure_links to push configuration onto live links. It is the only example that acts on live links without staging any file at all, so it previews by default, prints its own advisory, and its --apply is meant for a machine you can reach out of band. The default interface is lo, which is always up, so its link_state reports no change even on an empty host:
# systemd_networkd_activate.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Drive the daemon directly: ``link_state``, ``reload`` and lease renewal.
The write example chains its own reload, so this script is about the three
verbs that stand alone — and about the module's deliberate split between
*converging* and *stateless* operations:
* ``link_state`` reconciles the kernel ``IFF_UP`` flag with ``networkctl
up``/``down``. It reads ``NetworkdLinks`` and reports a change only when the
flag differs, so a converged host sends nothing. An interface absent from
the table raises ``OperationError`` rather than guessing.
* ``reload`` re-reads every ``.network``/``.netdev`` and reconfigures matching
links. It is **stateless** like ``apt.update``: there is no fact that records
"these links already have these files", so every pass reports a change and
runs the command. Convergence belongs to ``network_unit``; run this
deliberately, after units were staged by something else.
* ``reconfigure_links(renew=True)`` asks for a fresh DHCP lease (``networkctl
renew``), the remediation step with no file behind it at all. Without
``renew`` it runs ``networkctl reconfigure`` — re-apply the already-loaded
units to the named links, *without* re-reading the files, the distinction
``reload`` exists to draw.
**This example commands the running daemon, not just its files, so it
previews by default and its ``--apply`` is meant for a machine you can reach
out of band.** The default interface is ``lo``, which is always up — the
converged answer for it is "send nothing". ``link_state`` also takes a link
down (``up=False``); doing that to the interface carrying your SSH session
drops the connection.
Run it with::
uv run python examples/articles/systemd_networkd/systemd_networkd_activate.py
uv run python examples/articles/systemd_networkd/systemd_networkd_activate.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_activate.py --renew --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import execute, is_ubuntu, load_inventory, parser
DEFAULT_INTERFACE = "lo"
def build_deploy(interface=DEFAULT_INTERFACE, renew=False):
"""Build the remediation requests for one named interface."""
if not interface:
raise ValueError("an interface name is required")
def deploy(host):
yield op(
systemd_networkd.link_state,
name=f"Keep {interface} up",
interface=interface,
sudo=True,
when=is_ubuntu,
)
if renew:
yield op(
systemd_networkd.reconfigure_links,
name=f"Renew {interface}'s lease",
interfaces=(interface,),
renew=True,
sudo=True,
when=is_ubuntu,
)
else:
yield op(
systemd_networkd.reload,
name="Re-read networkd unit files",
sudo=True,
when=is_ubuntu,
)
return deploy
async def main(argv=None):
cli = parser(__doc__)
cli.add_argument(
"--interface",
default=DEFAULT_INTERFACE,
help="interface the link-state and renew requests name",
)
cli.add_argument(
"--renew",
action="store_true",
help="renew the interface's DHCP lease instead of reloading units",
)
args = cli.parse_args(argv)
print(
"Advisory: reload reconfigures every matching link, and renew asks the "
"server for a new lease. Read the preview first; keep this off the "
"interface carrying the session."
)
deploy = build_deploy(interface=args.interface, renew=args.renew)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
The preview shows the module's split between converging and stateless operations. The loopback is already up, so the link request reports no change and will send nothing; reload has no fact to compare against — nothing records "these links already have these files" — so it always reports a change and always yields its command:
Advisory: reload reconfigures every matching link, and renew asks the server for a new lease. Read the preview first; keep this off the interface carrying the session.
== Preview ==
ubuntu: Keep lo up [no change: link lo is already up]
ubuntu: Re-read networkd unit files [changed: networkctl reload will run]
Preview only; pass --apply to change the hosts.
The apply is the reload line and nothing else:
== Applied ==
ubuntu: Keep lo up [no change: link lo is already up]
ubuntu: Re-read networkd unit files [changed: networkctl reload will run]
$ sudo networkctl reload
A second --apply sends the reload again. That is correct behaviour for an activation command and the wrong thing to demo on a shared machine, which is why this script appears in neither workflow below. --renew swaps the reload for networkctl renew on the named interface — the lease-refusal remediation with no file behind it at all — and link_state(up=False) takes a link down, which is a real command on a real interface: done to the link carrying your SSH session, the session drops with it. An interface the host does not report raises OperationError rather than being silently skipped.
Remove the managed units
The article's units are named so they can be listed, and listed so they can be removed. This example loops over the same tuple the other scripts write, and never sweeps the directory:
# systemd_networkd_cleanup.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Remove every unit the systemd_networkd article manages."""
import asyncio
import sys
from pathlib import Path
from reemote import op, systemd_networkd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from systemd_networkd_article_common import (
MANAGED_UNITS,
execute,
is_ubuntu,
load_inventory,
parser,
)
def deploy(host):
for filename in MANAGED_UNITS:
yield op(
systemd_networkd.network_unit,
name=f"Remove {filename}",
filename=filename,
present=False,
sudo=True,
when=is_ubuntu,
)
async def main(argv=None):
args = parser(__doc__).parse_args(argv)
await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)
if __name__ == "__main__":
asyncio.run(main())
Every unit is present, so every request changes: thirteen elevated rm -f lines, each followed by a chained reload — except the .link, which the daemon never re-reads and which is therefore removed by the file comparison alone:
== Applied ==
ubuntu: Remove 60-reemote-eth1.network [changed: networkd unit /etc/systemd/network/60-reemote-eth1.network present, will remove]
$ sudo rm -f /etc/systemd/network/60-reemote-eth1.network
$ sudo networkctl reload
ubuntu: Remove 60-reemote-lab0.network [changed: networkd unit /etc/systemd/network/60-reemote-lab0.network present, will remove]
$ sudo rm -f /etc/systemd/network/60-reemote-lab0.network
$ sudo networkctl reload
ubuntu: Remove 60-reemote-lab1.network [changed: networkd unit /etc/systemd/network/60-reemote-lab1.network present, will remove]
$ sudo rm -f /etc/systemd/network/60-reemote-lab1.network
$ sudo networkctl reload
ubuntu: Remove 60-reemote-dhcp-eth2.network [changed: networkd unit /etc/systemd/network/60-reemote-dhcp-eth2.network present, will remove]
$ sudo rm -f /etc/systemd/network/60-reemote-dhcp-eth2.network
$ sudo networkctl reload
ubuntu: Remove 90-reemote-lan99.link [changed: networkd unit /etc/systemd/network/90-reemote-lan99.link present, will remove]
$ sudo rm -f /etc/systemd/network/90-reemote-lan99.link
ubuntu: Remove 61-reemote-rmbond0.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmbond0.netdev present, will remove]
$ sudo rm -f /etc/systemd/network/61-reemote-rmbond0.netdev
$ sudo networkctl reload
ubuntu: Remove 61-reemote-rmvlan110.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmvlan110.netdev present, will remove]
$ sudo rm -f /etc/systemd/network/61-reemote-rmvlan110.netdev
$ sudo networkctl reload
ubuntu: Remove 61-reemote-rmbr0.netdev [changed: networkd unit /etc/systemd/network/61-reemote-rmbr0.netdev present, will remove]
$ sudo rm -f /etc/systemd/network/61-reemote-rmbr0.netdev
$ sudo networkctl reload
ubuntu: Remove 62-reemote-eth3.network [changed: networkd unit /etc/systemd/network/62-reemote-eth3.network present, will remove]
$ sudo rm -f /etc/systemd/network/62-reemote-eth3.network
$ sudo networkctl reload
ubuntu: Remove 62-reemote-eth4.network [changed: networkd unit /etc/systemd/network/62-reemote-eth4.network present, will remove]
$ sudo rm -f /etc/systemd/network/62-reemote-eth4.network
$ sudo networkctl reload
ubuntu: Remove 63-reemote-rmbond0.network [changed: networkd unit /etc/systemd/network/63-reemote-rmbond0.network present, will remove]
$ sudo rm -f /etc/systemd/network/63-reemote-rmbond0.network
$ sudo networkctl reload
ubuntu: Remove 63-reemote-rmvlan110.network [changed: networkd unit /etc/systemd/network/63-reemote-rmvlan110.network present, will remove]
$ sudo rm -f /etc/systemd/network/63-reemote-rmvlan110.network
$ sudo networkctl reload
ubuntu: Remove 63-reemote-rmbr0.network [changed: networkd unit /etc/systemd/network/63-reemote-rmbr0.network present, will remove]
$ sudo rm -f /etc/systemd/network/63-reemote-rmbr0.network
$ sudo networkctl reload
A second run reports no change for all thirteen units and sends nothing at all:
== Applied ==
ubuntu: Remove 60-reemote-eth1.network [no change: networkd unit already absent (/etc/systemd/network/60-reemote-eth1.network)]
ubuntu: Remove 60-reemote-lab0.network [no change: networkd unit already absent (/etc/systemd/network/60-reemote-lab0.network)]
ubuntu: Remove 60-reemote-lab1.network [no change: networkd unit already absent (/etc/systemd/network/60-reemote-lab1.network)]
ubuntu: Remove 60-reemote-dhcp-eth2.network [no change: networkd unit already absent (/etc/systemd/network/60-reemote-dhcp-eth2.network)]
ubuntu: Remove 90-reemote-lan99.link [no change: networkd unit already absent (/etc/systemd/network/90-reemote-lan99.link)]
ubuntu: Remove 61-reemote-rmbond0.netdev [no change: networkd unit already absent (/etc/systemd/network/61-reemote-rmbond0.netdev)]
ubuntu: Remove 61-reemote-rmvlan110.netdev [no change: networkd unit already absent (/etc/systemd/network/61-reemote-rmvlan110.netdev)]
ubuntu: Remove 61-reemote-rmbr0.netdev [no change: networkd unit already absent (/etc/systemd/network/61-reemote-rmbr0.netdev)]
ubuntu: Remove 62-reemote-eth3.network [no change: networkd unit already absent (/etc/systemd/network/62-reemote-eth3.network)]
ubuntu: Remove 62-reemote-eth4.network [no change: networkd unit already absent (/etc/systemd/network/62-reemote-eth4.network)]
ubuntu: Remove 63-reemote-rmbond0.network [no change: networkd unit already absent (/etc/systemd/network/63-reemote-rmbond0.network)]
ubuntu: Remove 63-reemote-rmvlan110.network [no change: networkd unit already absent (/etc/systemd/network/63-reemote-rmvlan110.network)]
ubuntu: Remove 63-reemote-rmbr0.network [no change: networkd unit already absent (/etc/systemd/network/63-reemote-rmbr0.network)]
and the final inspection is back where the article started — no admin-owned files under /etc/systemd/network, lo still unmanaged and up:
== ubuntu ==
units: (no admin-owned files under /etc/systemd/network)
managed units:
/etc/systemd/network/60-reemote-eth1.network: absent
/etc/systemd/network/60-reemote-lab0.network: absent
/etc/systemd/network/60-reemote-lab1.network: absent
/etc/systemd/network/60-reemote-dhcp-eth2.network: absent
/etc/systemd/network/90-reemote-lan99.link: absent
/etc/systemd/network/61-reemote-rmbond0.netdev: absent
/etc/systemd/network/61-reemote-rmvlan110.netdev: absent
/etc/systemd/network/61-reemote-rmbr0.netdev: absent
/etc/systemd/network/62-reemote-eth3.network: absent
/etc/systemd/network/62-reemote-eth4.network: absent
/etc/systemd/network/63-reemote-rmbond0.network: absent
/etc/systemd/network/63-reemote-rmvlan110.network: absent
/etc/systemd/network/63-reemote-rmbr0.network: absent
links known to networkctl:
lo: unmanaged, up, (no unit matched)
manager configuration:
(default: every row commented out)
On a live link, the chained reload after a removal is what withdraws the unit's effect: the link comes back with no configuration file. The lab interfaces named here never had one, so the reload costs nothing and proves the same point the writes did — every change the module makes is a function of what the host actually holds.
Test the examples, then check convergence
The focused pytest suite imports every script, validates the inventory it reads, runs each deploy twice against a persistent simulated host, replays the sequences below and checks that the article's Python fences match the runnable files:
.venv/bin/python -m pytest -q tests/test_systemd_networkd_article_examples.py
For the real Ubuntu host, preview every script first, then apply the configuration examples in this order:
uv run python examples/articles/systemd_networkd/systemd_networkd_hello.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_service.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_static.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_rendered.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_dhcp.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_bond.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_inspect.py --check
Then repeat them. Every command below should report no changes and send no commands:
uv run python examples/articles/systemd_networkd/systemd_networkd_hello.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_service.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_static.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_rendered.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_dhcp.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_bond.py --apply
systemd_networkd_activate.py is deliberately absent from both lists: its reload request is stateless, so a second pass reports a change and runs the command again, which is the correct behaviour for an activation verb and the wrong thing to demonstrate on a shared machine. Preview it, and apply it only where you can reach the host by another path. Finish by removing the units and proving the removal converges:
uv run python examples/articles/systemd_networkd/systemd_networkd_cleanup.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_cleanup.py --apply
uv run python examples/articles/systemd_networkd/systemd_networkd_inspect.py
The second systemd_networkd_cleanup.py pass reports no change for all thirteen units, and the final inspection lists nothing under /etc/systemd/network.
Implementation summary
Reemote's systemd_networkd support is four facts and four operations built around one disciplined write. NetworkdUnits lists /etc/systemd/network in a single round trip as filename to kind/path/mode; NetworkdUnitFile returns one unit's raw text, distinguishing absent, empty and unreadable; NetworkdLinks projects networkctl list --json=short into per-interface state including the unit file each link matched, wherever it lives; and NetworkdConfig flattens the effective networkd.conf plus drop-ins into Section.Key. network_unit holds a whole file: it compares the wanted text against that read-back, spools changed content to a destination-derived /tmp directory as the login user, installs it in one elevated shell step as root:root mode 0644, and chains networkctl reload only when the write actually changed a .network or .netdev — the handler exists only as a conditional command inside the same request, suppressed by reload=False when a group should reload once. Removal runs through the same read-back gate with present=False. link_state is the other converging operation, reconciling the kernel IFF_UP flag and raising on an interface the host does not report; reload and reconfigure_links are stateless by design and always report a change.
The practical result is a networkd workflow with no templates, no handlers and no YAML library in the base dependency set. A unit is a hashable string argument in an ordinary Python function, the preview shows the real host state every decision came from — which files differ, which links are up, whether a reload will run — and a second pass writes nothing for the file operations while the activation verbs stay explicit and separately scheduled. Daemon enablement stays where it belongs, in systemd.service; competing managers stay untouched; netplan's rendered /run state stays readable through the same facts that judge the writes. The module reference lists the complete API, and the examples index describes the shared real-host execution contract.
References
systemd-networkd background
- systemd.network(5) manual page
- systemd.netdev(5) manual page
- systemd.link(5) manual page
- networkctl(1) manual page
- Systemd-networkd (Arch wiki)
Reemote documentation: https://reemote.org/
Install:
pip install reemote(Python 3.13+)License: EPL-2.0
Discord: https://discord.gg/de8MqzA3E
Top comments (0)