DEV Community

Kim Jarvis
Kim Jarvis

Posted on Originally published at reemote.hashnode.dev

How to use Python and netplan to configure static IP addresses

Netplan is the network configuration layer Ubuntu and several other distributions ship by default. Its state is a handful of YAML files under /etc/netplan: each file describes devices — Ethernet links, Wi-Fi interfaces, VLANs, bridges, bonds — with addresses, routes, name servers and DHCP behaviour. A generator merges those files and hands the result to systemd-networkd or to NetworkManager, and the netplan command line exposes the merge (netplan get), the render (netplan generate), the activation (netplan apply) and a self-reverting variant of it (netplan try).

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 netplan module is written in that spirit: it owns the drop-in files and the netplan CLI calls, and nothing else. It needs no agent, no interpreter and no template file on the managed machine — only the netplan install the distribution already provides, plus a POSIX shell and an SSH connection.

This article builds a set of examples that manage static IPv4 addressing, DHCP links with predictable outcomes, VLANs and a bridge, and finally the activation step, and runs each 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
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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 netplan configures a network

A netplan file is one YAML document rooted at network. Its minimal static-IPv4 shape is short enough to keep in your head:

network:
  version: 2
  renderer: networkd
  ethernets:
    eth0:
      dhcp4: false
      addresses:
        - 192.168.1.20/24
      routes:
        - to: default
          via: 192.168.1.1
      nameservers:
        addresses:
          - 192.168.1.10
          - 9.9.9.9
Enter fullscreen mode Exit fullscreen mode

Five properties of that layout decide how an automation tool has to treat it.

  • The configuration is a set of files, not one file. Every *.yaml under /etc/netplan is read and merged in lexicographic order, so 50-cloud-init.yaml is merged before 60-custom.yaml, and a key set by the later file wins for the device it names. This is why vendor cloud images ship a numbered file and local policy is expected to arrive in a higher-numbered one: you add a drop-in rather than editing the vendor's.
  • Devices are grouped by type. ethernets are physical links, wifis carry SSIDs and credentials, vlans name a parent through link and a tag through id, bridges and bonds collect member devices. A VLAN is not a property of an Ethernet entry; it is its own document key, and a bridge member has to be listed under interfaces to be enslaved.
  • Addresses and routes are lists of structured entries. One interface can hold several addresses, and an address can carry a label for a secondary alias. Each route is a mapping with to, via and an optional metric, and the lowest metric wins when several default routes exist — which is how a host with two uplinks picks one without any routing daemon.
  • Reading a file needs root. Netplan files are mode 0600 and owned by root because they can hold Wi-Fi pre-shared keys. The /etc/netplan directory itself is world-readable, so a listing is cheap while the content is not, and netplan get typically has to run elevated too.
  • Writing is not applying. netplan generate parses every drop-in and renders the backend's state under /run; netplan apply pushes that state into the running stack — restarting interfaces, replacing addresses and rewriting /etc/resolv.conf. netplan try --timeout N applies the same way but reverts automatically unless the change is confirmed inside the window, which is the only sane way to edit the interface carrying your own SSH session.

The netplan YAML reference, its worked examples and the Debian wiki page cover the grammar in more detail; the references at the end list all four sources this article's shape follows.

The Reemote netplan module

The netplan module reads state and manages files; it deliberately keeps activation separate. Its facts answer the four questions worth asking before a change: what the merged configuration currently is, which renderer the host has selected, which drop-ins exist and in what merge order, and what one named file contains. Every one of them reads through the same two-tier probe — the plain command first, then the escalation tool from the inventory when the login user is refused — because a 0600 file returns a refusal rather than an empty answer.

Its operations are one write, one removal and one activation. netplan.config owns a whole drop-in: you hand it the finished YAML text and a path, it compares that text against what the file actually holds, and only on a real difference does it transfer and install the file — root-owned, mode 0600 by default — and follow the write with netplan generate so a malformed document fails the deploy without ever reaching the live stack. netplan.absent removes one named file, and nothing else in the directory. netplan.apply is the only operation that changes the running network, either directly or as netplan try with a rollback window.

Three boundaries matter when composing it. The module does not install netplan or own the network daemon: pair it with the apt, dnf or apk module for packages and with systemd_networkd when you need systemd-networkd units of your own. It manages whole files, not keys: there is no set this address operation, because a netplan document is a tree whose siblings you must not silently drop. And because a mistake on a live interface can sever the session, the module never applies on your behalf — a config request that succeeds leaves the running host exactly as it was.

Managing a static IP address in Python

A static-IP change is three jobs: write a numbered drop-in, prove it parses with netplan generate, and activate it. Reemote needs no template file for any of them, since the YAML text is produced where the deploy runs:

  • Writing a finished document: op(netplan.config, path=..., content=DOCUMENT, sudo=True).
  • Building that document from host values: a Python render function, then the same netplan.config request.
  • Handling a set of interfaces: an ordinary Python loop yielding one request per drop-in.
  • Validating before activation: built into netplan.config (validate=True is the default).
  • Removing one managed file: op(netplan.absent, path=..., sudo=True).
  • Activating the configuration: op(netplan.apply, sudo=True).
  • Activating with a rollback window: op(netplan.apply, use_try=True, timeout=120, sudo=True).
  • Limiting the change to one OS family: when=is_ubuntu on the request.
  • Reading the merged configuration back: the NetplanConfig fact, or gather_fact across the fleet.
  • Reporting what actually changed: the module's own answer — config changes only on a real delta, apply always.

Two conventions carry through every example below. Arguments passed to op() must stay hashable, so sequences are tuples and the YAML body is a plain string; 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 netplan 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"
    },
    "group": "ubuntu",
    "tags": ["ubuntu_host", "apt_package_manager"]
  }
]
Enter fullscreen mode Exit fullscreen mode

Replace the address, user and key path with your own. Every managed request writes under /etc/netplan, 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. Check what the host already has before you start, because the vendor file is not yours to overwrite:

ssh supervisor@192.168.0.251 'ls -l /etc/netplan; sudo netplan get | head -40'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

The scripts under examples/articles/netplan/ 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, netplan_article_common.py, which holds the drop-in paths and the preview/apply driver.

Example Article concept
netplan_hello.py The canonical two operations against persistent SSH hosts
netplan_static_ip.py One static IPv4 address, route and resolver set in a drop-in
netplan_rendered.py Render the document from a Python table instead of a template
netplan_dhcp.py Two DHCP links with a preferred gateway and resolver
netplan_vlan.py VLANs on a parent link and a bridge over one of them
netplan_inspect.py Read back renderer, files, per-file presence and the merged document
netplan_apply_try.py Activate the configuration, with or without a rollback window
netplan_cleanup.py Remove every drop-in the article manages

Every example below names interfaces the lab host does not have — eth1, lab1 … lab5 — and marks them optional: true, so a written drop-in is inert and the sequence can be run repeatedly on a machine you are logged into. Point a device name 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/netplan/netplan_static_ip.py
Enter fullscreen mode Exit fullscreen mode

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.

# netplan_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 netplan_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())
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Write one static IPv4 address

One netplan.config request is the whole static-IP story: a complete YAML document for a numbered drop-in. The 60 prefix sorts after the vendor's 50-cloud-init.yaml, so this file merges last and wins for the device it declares, while the vendor's configuration for eth0 is left alone.

# netplan_static_ip.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Write one static-IPv4 netplan drop-in with ``netplan.config``.

The example manages ``/etc/netplan/60-reemote-static.yaml``: a complete YAML
document, written verbatim, that gives a lab interface a static address, a
default route and two resolvers. The ``60`` prefix sorts after the vendor's
``50-cloud-init.yaml``, so this file merges last and wins for the device it
declares.

``netplan.config`` compares the desired text against what ``NetplanFile`` reads
back and yields nothing when they match. A changed write is a spool transfer plus
an elevated install, followed by ``netplan generate`` because ``validate``
defaults to ``True``: the generator parses every drop-in and renders ``/run``
state, so a malformed document fails the deploy here instead of reaching the
running stack.

**Nothing in this example touches the live network.** Writing a drop-in changes
what the host *would* configure; ``netplan apply`` changes what it *does*. The
addressed device is ``eth1``, which the lab host does not have, and it is marked
``optional: true`` so a missing device never blocks boot. Point ``eth1`` at a
real interface only on a machine you can reach out of band, and use the rollback
window shown by ``netplan_apply_try.py``.

Run it with::

    uv run python examples/articles/netplan/netplan_static_ip.py
    uv run python examples/articles/netplan/netplan_static_ip.py --apply
"""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import (
    STATIC_DROPIN,
    execute,
    is_ubuntu,
    load_inventory,
    parser,
)

STATIC_CONTENT = """\
# Managed by Reemote. Do not edit by hand.
network:
  version: 2
  renderer: networkd
  ethernets:
    eth1:
      dhcp4: false
      dhcp6: false
      optional: true
      addresses:
        - 10.30.0.11/24
      routes:
        - to: default
          via: 10.30.0.1
      nameservers:
        search:
          - lab.example
        addresses:
          - 1.1.1.1
          - 9.9.9.9
"""


def deploy(host):
    yield op(
        netplan.config,
        name="Configure a static IPv4 address on eth1",
        path=STATIC_DROPIN,
        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())
Enter fullscreen mode Exit fullscreen mode

Review the plan, then apply it. The first pass writes the file and validates it; the preview reports the reason it collected, which names the file and says whether the generator will run:

== Preview ==
ubuntu: Configure a static IPv4 address on eth1 [changed: netplan config /etc/netplan/60-reemote-static.yaml is absent, will install, will validate with netplan generate]
Preview only; pass --apply to change the hosts.
Enter fullscreen mode Exit fullscreen mode

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 validation:

== Applied ==
ubuntu: Configure a static IPv4 address on eth1 [changed: netplan config /etc/netplan/60-reemote-static.yaml is absent, will install, will validate with netplan generate]
    $ scp <netplan conf> -> /tmp/reemote-netplan-0b249e0616640240/config.yaml
    $ sudo sh -c 'mkdir -p /etc/netplan && cp /tmp/reemote-netplan-0b249e0616640240/config.yaml /etc/netplan/60-reemote-static.yaml && chmod 600 /etc/netplan/60-reemote-static.yaml && rm -rf /tmp/reemote-netplan-0b249e0616640240'
    $ sudo netplan generate
Enter fullscreen mode Exit fullscreen mode

Running the same script again sends nothing. netplan.config compares the desired text with what NetplanFile reads back through the elevated tier, so an unchanged file is not rewritten, not re-uploaded and not re-validated:

== Preview ==
ubuntu: Configure a static IPv4 address on eth1 [no change: netplan config already up to date (/etc/netplan/60-reemote-static.yaml)]
== Applied ==
ubuntu: Configure a static IPv4 address on eth1 [no change: netplan config already up to date (/etc/netplan/60-reemote-static.yaml)]
Enter fullscreen mode Exit fullscreen mode

That is the whole convergence story for the write family: the second pass reports no change and issues no commands, and the installed file ends up root:root mode 0600 — the ownership netplan requires and the mode a Wi-Fi key needs.

Render the drop-in on the control side

A template file cannot survive contact with this model: netplan.config takes finished text, so the loop, the conditionals and the indentation live on the control side, in ordinary Python. The next example keeps the addressing in a table of tuples and builds the document from it — plus a labelled secondary address and two default routes whose metrics decide which gateway is preferred.

# netplan_rendered.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Render a netplan drop-in on the control side instead of templating it.

A configuration-management deploy normally ships a template file plus a list of
dictionaries and lets the target render them together. Reemote has no template
operation on the target: ``netplan.config`` takes the finished YAML 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, and the function
turns it into the exact bytes the file will contain — including a labelled
secondary address and two default routes whose ``metric`` values decide which
gateway is preferred.

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. The example writes one drop-in,
``/etc/netplan/60-reemote-lab.yaml``, for two absent lab devices marked
``optional: true``, so the file is inert until it names a real interface.

Run it with::

    uv run python examples/articles/netplan/netplan_rendered.py
    uv run python examples/articles/netplan/netplan_rendered.py --apply
"""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import (
    LAB_DROPIN,
    execute,
    is_ubuntu,
    load_inventory,
    parser,
)

# (device, addresses, routes) with ``(address, label)`` and
# ``(destination, gateway, metric)`` rows. ``None`` means "omit the field".
LAB_INTERFACES = (
    (
        "lab1",
        (("10.30.10.11/24", None), ("10.30.10.12/24", "lab1:alias")),
        (("default", "10.30.10.1", 100),),
    ),
    (
        "lab2",
        (("10.30.20.11/24", None),),
        (("default", "10.30.20.1", 200), ("10.31.0.0/24", "10.30.20.254", None)),
    ),
)
NAMESERVERS = ("1.1.1.1", "9.9.9.9")


def _render_addresses(entries):
    rows = []
    for address, label in entries:
        if label is None:
            rows.append(f"        - {address}")
        else:
            rows.append(f'        - {address}:\n            label: "{label}"')
    return rows


def _render_routes(entries):
    rows = []
    for destination, gateway, metric in entries:
        rows.append(f"        - to: {destination}\n          via: {gateway}")
        if metric is not None:
            rows.append(f"          metric: {metric}")
    return rows


def _render_interface(device, addresses, routes, nameservers):
    rows = [
        f"    {device}:",
        "      dhcp4: false",
        "      dhcp6: false",
        "      optional: true",
        "      addresses:",
        *_render_addresses(addresses),
        "      routes:",
        *_render_routes(routes),
        "      nameservers:",
        "        addresses:",
    ]
    rows.extend(f"          - {server}" for server in nameservers)
    return rows


def render_document(interfaces, nameservers):
    """Build the whole drop-in text from the interface table."""
    rows = [
        "# Managed by Reemote. Rendered on the control side.",
        "network:",
        "  version: 2",
        "  renderer: networkd",
        "  ethernets:",
    ]
    for device, addresses, routes in interfaces:
        rows.extend(_render_interface(device, addresses, routes, nameservers))
    return "\n".join(rows) + "\n"


DOCUMENT = render_document(LAB_INTERFACES, NAMESERVERS)


def deploy(host):
    yield op(
        netplan.config,
        name="Render the lab addressing",
        path=LAB_DROPIN,
        content=DOCUMENT,
        mode="0600",
        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())
Enter fullscreen mode Exit fullscreen mode

The rendered text is a module constant, so the preview and the apply agree byte for byte, and the same document is what a unit test can assert against without a host. For the table above it produces:

# Managed by Reemote. Rendered on the control side.
network:
  version: 2
  renderer: networkd
  ethernets:
    lab1:
      dhcp4: false
      dhcp6: false
      optional: true
      addresses:
        - 10.30.10.11/24
        - 10.30.10.12/24:
            label: "lab1:alias"
      routes:
        - to: default
          via: 10.30.10.1
          metric: 100
      nameservers:
        addresses:
          - 1.1.1.1
          - 9.9.9.9
    lab2:
      dhcp4: false
      dhcp6: false
      optional: true
      addresses:
        - 10.30.20.11/24
      routes:
        - to: default
          via: 10.30.20.1
          metric: 200
        - to: 10.31.0.0/24
          via: 10.30.20.254
      nameservers:
        addresses:
          - 1.1.1.1
          - 9.9.9.9
Enter fullscreen mode Exit fullscreen mode

lab1 and lab2 both offer a default route; the metrics make lab1 the preference and keep lab2 as the failover. The route to 10.31.0.0/24 carries no metric at all, because a more specific destination is chosen on length, not on cost.

Keep two DHCP links on predictable terms

Static addressing is only half of a real host. Two links that stay on DHCP still need their outcome pinned down, or the lease that arrives last decides the gateway and the resolver. This example manages a pair of drop-ins, written as a loop over a tuple of (path, text) pairs, and validates the group once at the end.

# netplan_dhcp.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Keep two interfaces on DHCP while pinning which gateway and resolver win.

Static addressing is only half of a real host's network. This example manages a
pair of drop-ins that stay on DHCP but make the outcome predictable:

* ``match`` plus ``set-name`` renames whichever NIC carries the given address, so
  the configuration survives a rename of the kernel's prediction;
* ``dhcp4-overrides.route-metric`` orders the two default routes, so traffic
  leaves through the preferred link even though both offer a gateway;
* ``use-dns: false`` on the backup link stops its lease from replacing the
  resolvers the primary link installed;
* ``accept-ra: false`` and ``link-local: []`` mute IPv6 on a device that should be
  reachable only through its configured address;
* ``optional: true`` keeps a missing device from stalling the boot.

The group is written with ``validate=False`` on every request but the last,
because ``netplan generate`` parses *every* drop-in: one validation at the end of
a group costs the same as one per file and reports a broken sibling too. Both
devices are lab names the host does not have, so nothing here changes the running
network even after an apply.

Run it with::

    uv run python examples/articles/netplan/netplan_dhcp.py
    uv run python examples/articles/netplan/netplan_dhcp.py --apply
"""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import (
    DHCP_DROPINS,
    execute,
    is_ubuntu,
    load_inventory,
    parser,
)

DHCP_LINKS = (
    (
        DHCP_DROPINS[0],
        """\
# Managed by Reemote. Primary DHCP link.
network:
  version: 2
  renderer: networkd
  ethernets:
    lab3:
      match:
        macaddress: "52:54:00:aa:bb:cc"
      set-name: lab3
      dhcp4: true
      dhcp6: false
      optional: true
      dhcp4-overrides:
        route-metric: 100
""",
    ),
    (
        DHCP_DROPINS[1],
        """\
# Managed by Reemote. Backup DHCP link.
network:
  version: 2
  renderer: networkd
  ethernets:
    lab4:
      dhcp4: true
      dhcp6: false
      optional: true
      accept-ra: false
      link-local: []
      dhcp4-overrides:
        route-metric: 200
        use-dns: false
""",
    ),
)


def deploy(host):
    last = len(DHCP_LINKS) - 1
    for index, (path, content) in enumerate(DHCP_LINKS):
        yield op(
            netplan.config,
            name=f"Configure DHCP on {path.rsplit('/', 1)[-1].removesuffix('.yaml')}",
            path=path,
            content=content,
            validate=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())
Enter fullscreen mode Exit fullscreen mode

netplan generate parses every file, so validating after the last write costs the same command as validating after each one — and reports a broken sibling too. The preview shows that asymmetry in the reasons: only the final request mentions the generator.

== Preview ==
ubuntu: Configure DHCP on 60-reemote-dhcp-lab3 [changed: netplan config /etc/netplan/60-reemote-dhcp-lab3.yaml is absent, will install]
ubuntu: Configure DHCP on 60-reemote-dhcp-lab4 [changed: netplan config /etc/netplan/60-reemote-dhcp-lab4.yaml is absent, will install, will validate with netplan generate]
Enter fullscreen mode Exit fullscreen mode

After --apply, the two files sit in /etc/netplan and the third pass reports both as up to date. The knobs themselves are the point: match plus set-name renames whichever NIC carries the given MAC, so the configuration survives a change in the kernel's naming prediction; dhcp4-overrides.route-metric orders the two default routes so the primary link's gateway is preferred; use-dns: false stops the backup lease from replacing the resolvers the primary link installed; and accept-ra: false with link-local: [] mutes IPv6 on a device that should be reachable only through its configured address.

Layer VLANs and a bridge

Netplan describes devices by their type, so a tagged subinterface lives under vlans, names its parent through link and its tag through id, and a bridge collects members under interfaces. All three levels belong in one document, because a VLAN no file declares as a bridge member is simply a separate interface:

# netplan_vlan.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Layer VLANs and a bridge on a parent interface with one drop-in.

Netplan describes devices by their type, not by their order in the file: an
``ethernets:`` entry is a physical link, ``vlans:`` holds tagged subinterfaces
that name their parent through ``link`` and their tag through ``id``, and
``bridges:`` collects member devices. All three belong in one document, because a
VLAN that no file declares as a member of a bridge is simply a separate interface.

The example manages ``/etc/netplan/60-reemote-vlans.yaml``: an unaddressed parent
(``lab5``), two tagged children with their own subnets and a route on one of
them, and a bridge carrying the first VLAN. Every device is optional, so the
whole tree is inert on a host that has no ``lab5`` — which is exactly the state
this lab runs in. Reading it back is the point of ``netplan_inspect.py``: the
merged ``netplan get`` document shows the parent and its children together, no
matter which file contributed each of them.

Run it with::

    uv run python examples/articles/netplan/netplan_vlan.py
    uv run python examples/articles/netplan/netplan_vlan.py --apply
"""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import (
    VLAN_DROPIN,
    execute,
    is_ubuntu,
    load_inventory,
    parser,
)

VLAN_CONTENT = """\
# Managed by Reemote. One parent, two VLANs, one bridge.
network:
  version: 2
  renderer: networkd
  ethernets:
    lab5:
      dhcp4: false
      dhcp6: false
      optional: true
  vlans:
    lab5.100:
      id: 100
      link: lab5
      addresses:
        - 10.100.0.10/24
    lab5.200:
      id: 200
      link: lab5
      addresses:
        - 10.200.0.10/24
      routes:
        - to: 10.201.0.0/24
          via: 10.200.0.1
  bridges:
    br-lab:
      optional: true
      interfaces:
        - lab5.100
      addresses:
        - 172.30.100.1/24
"""


def deploy(host):
    yield op(
        netplan.config,
        name="Ensure the VLAN and bridge layout",
        path=VLAN_DROPIN,
        content=VLAN_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())
Enter fullscreen mode Exit fullscreen mode

The parent lab5 gets no address — it exists to carry its children. lab5.100 and lab5.200 hold their own subnets, one of them also a route to a remote through the VLAN's gateway, and br-lab enslaves lab5.100 with an address of its own. One request writes the lot, and one validation covers it:

== Applied ==
ubuntu: Ensure the VLAN and bridge layout [changed: netplan config /etc/netplan/60-reemote-vlans.yaml is absent, will install, will validate with netplan generate]
    $ scp <netplan conf> -> /tmp/reemote-netplan-8169e8f6d8b47555/config.yaml
    $ sudo sh -c 'mkdir -p /etc/netplan && cp /tmp/reemote-netplan-8169e8f6d8b47555/config.yaml /etc/netplan/60-reemote-vlans.yaml && chmod 600 /etc/netplan/60-reemote-vlans.yaml && rm -rf /tmp/reemote-netplan-8169e8f6d8b47555'
    $ sudo netplan generate
Enter fullscreen mode Exit fullscreen mode

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 drop-in the article manages exists.

# netplan_inspect.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Read back what netplan actually holds, using the four netplan facts.

This script mutates nothing. It gathers the four facts the ``netplan`` module
offers:

* ``NetplanRenderer`` — ``networkd`` or ``NetworkManager``, the one scalar worth
  reading before touching a host, since a desktop box and a server box behave
  differently once a configuration is applied;
* ``NetplanFiles`` — the YAML files in ``/etc/netplan``, sorted, which is also the
  order netplan merges them;
* ``NetplanFile`` — the raw text of one file, so a managed drop-in can be checked
  for presence without parsing the merged document;
* ``NetplanConfig`` — the merged ``netplan get`` document, which is what the
  generator will act on regardless of which file contributed each key.

Each fact reads through the ``netplan get`` or ``cat`` form behind the firewall
family's two-tier elevation, because netplan files are ``0600`` root-owned: the
login user is refused, and the elevated re-read answers. Pass ``--check`` to exit
nonzero until every drop-in this article manages is present.

Run it with::

    uv run python examples/articles/netplan/netplan_inspect.py
    uv run python examples/articles/netplan/netplan_inspect.py --check
"""

import asyncio
import sys
import textwrap
from pathlib import Path

from reemote import (
    Host,
    NetplanConfig,
    NetplanFile,
    NetplanFiles,
    NetplanRenderer,
    gather_fact,
)

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import MANAGED_DROPINS, load_inventory, parser


async def collect(hosts):
    """Gather all four fact groups across the hosts and align them per host."""
    renderers = await gather_fact(hosts, NetplanRenderer)
    listings = await gather_fact(hosts, NetplanFiles)
    merged = await gather_fact(hosts, NetplanConfig)
    managed = {}
    for path in MANAGED_DROPINS:
        texts = await gather_fact(hosts, NetplanFile, path)
        managed[path] = {name: text is not None for name, text in texts.items()}
    rows = {}
    for host in hosts:
        rows[host.name] = {
            "renderer": renderers[host.name] or "networkd (netplan's default)",
            "files": listings[host.name],
            "managed": {path: flags[host.name] for path, flags in managed.items()},
            "config": merged[host.name] or "(no readable netplan configuration)",
        }
    return rows


def managed_are_present(rows):
    """Whether every managed drop-in 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 drop-in 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} ==")
        print(f"renderer: {row['renderer']}")
        print("files, in merge order:")
        for path in row["files"]:
            kind = "managed" if path in MANAGED_DROPINS else "unmanaged"
            print(f"  {path}  [{kind}]")
        print("managed drop-ins:")
        for path, present in row["managed"].items():
            print(f"  {path}: {'present' if present else 'absent'}")
        print("merged configuration:")
        print(textwrap.indent(row["config"], "  "))

    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 drop-in is present")
    return rows


if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

NetplanFiles answers in the order the generator merges, which is why 50-cloud-init.yaml leads the listing; NetplanFile answers per file so a managed drop-in can be checked without parsing anything; NetplanConfig answers the merged document, which is what the backend will act on regardless of which file contributed each key; and NetplanRenderer answers the one scalar worth knowing before a change — a host running NetworkManager behaves very differently from one running systemd-networkd once a configuration is applied.

== ubuntu ==
renderer: networkd
files, in merge order:
  /etc/netplan/50-cloud-init.yaml  [unmanaged]
  /etc/netplan/60-reemote-dhcp-lab3.yaml  [managed]
  /etc/netplan/60-reemote-dhcp-lab4.yaml  [managed]
  /etc/netplan/60-reemote-lab.yaml  [managed]
  /etc/netplan/60-reemote-static.yaml  [managed]
  /etc/netplan/60-reemote-vlans.yaml  [managed]
managed drop-ins:
  /etc/netplan/60-reemote-static.yaml: present
  /etc/netplan/60-reemote-lab.yaml: present
  /etc/netplan/60-reemote-dhcp-lab3.yaml: present
  /etc/netplan/60-reemote-dhcp-lab4.yaml: present
  /etc/netplan/60-reemote-vlans.yaml: present
merged configuration:
  network:
    version: 2
    renderer: networkd
every managed drop-in is present
Enter fullscreen mode Exit fullscreen mode

Before any of the examples ran, the same listing showed the vendor file only, 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.

Activate the configuration

Every request above staged a file; none of them changed the network. This last mutating example is the one that would, so it previews by default and documents the risk in its own docstring.

# netplan_apply_try.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Activate the configuration with ``netplan apply`` under a rollback window.

``netplan.apply`` is the module's one **stateless** operation: it reads no fact,
always reports a change and always yields its command, because "the running stack
already matches the disk" is not cheap to observe. That is why the namespace
splits writing from applying — ``config`` never applies by itself, and a deploy
expresses the sequencing by yielding ``apply`` as its own request after the
writes it should follow.

``use_try=True`` asks for ``netplan try --timeout <n>`` instead of ``netplan
apply``. netplan stages the configuration and reverts it unless the change is
confirmed before the window closes — by pressing Enter on the host, or by a
``SIGUSR1``/``SIGINT`` sent over a *second*, out-of-band channel. That is the
difference between a risky edit and a lost host: a mistake on the interface
carrying this SSH session heals itself after ``timeout`` seconds rather than
waiting for a console.

**This is the only example in the article that would change the live network, so
it previews by default and its ``--apply`` is meant for a machine you can reach
out of band.** The lab drop-ins name interfaces the host does not have, so even
an applied try re-renders nothing that is carrying the session.

Run it with::

    uv run python examples/articles/netplan/netplan_apply_try.py
    uv run python examples/articles/netplan/netplan_apply_try.py --direct
    uv run python examples/articles/netplan/netplan_apply_try.py --apply
"""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import execute, is_ubuntu, load_inventory, parser

DEFAULT_TIMEOUT = 90


def build_deploy(use_try=True, timeout=DEFAULT_TIMEOUT):
    """Build the apply request: a rollback window by default, a direct apply on request."""
    if timeout <= 0:
        raise ValueError(f"netplan try timeout must be a positive integer, got {timeout}")

    def deploy(host):
        yield op(
            netplan.apply,
            name=(
                "Apply netplan with a rollback window"
                if use_try
                else "Apply netplan configuration"
            ),
            use_try=use_try,
            timeout=timeout,
            sudo=True,
            when=is_ubuntu,
        )

    return deploy


async def main(argv=None):
    cli = parser(__doc__)
    cli.add_argument(
        "--direct",
        action="store_true",
        help="run netplan apply instead of netplan try",
    )
    cli.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT)
    args = cli.parse_args(argv)
    deploy = build_deploy(use_try=not args.direct, timeout=args.timeout)
    print(
        "Advisory: applying rewrites addresses, routes and name servers. "
        "Read the preview, and confirm the try window from a second channel."
    )
    await execute(load_inventory(args.inventory), deploy, apply_changes=args.apply)


if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

The default is netplan try, and the log says so in the reason line, because the operation is stateless: it reports a change on every pass and always yields its command.

Advisory: applying rewrites addresses, routes and name servers. Read the preview, and confirm the try window from a second channel.
== Preview ==
ubuntu: Apply netplan with a rollback window [changed: netplan try (rollback after 90s)]
Preview only; pass --apply to change the hosts.
Enter fullscreen mode Exit fullscreen mode
== Applied ==
ubuntu: Apply netplan with a rollback window [changed: netplan try (rollback after 90s)]
    $ sudo netplan try --timeout 90
Enter fullscreen mode Exit fullscreen mode

netplan try stages the configuration and reverts it unless the change is confirmed before the window closes — by pressing Enter on the host, or by a SIGUSR1 or SIGINT delivered over a second, out-of-band channel. That is the difference between a risky edit and a lost machine: a mistake on the interface carrying this session heals itself after timeout seconds instead of waiting for a console. --direct asks for the plain netplan apply instead, which is what a reprovisioning run wants and an interactive session does not.

Remove the managed drop-ins

The article's files are numbered 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:

# netplan_cleanup.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Remove every drop-in the netplan article manages."""

import asyncio
import sys
from pathlib import Path

from reemote import netplan, op

sys.path.insert(0, str(Path(__file__).resolve().parent))
from netplan_article_common import (
    MANAGED_DROPINS,
    execute,
    is_ubuntu,
    load_inventory,
    parser,
)


def deploy(host):
    for path in MANAGED_DROPINS:
        yield op(
            netplan.absent,
            name=f"Remove {path.rsplit('/', 1)[-1]}",
            path=path,
            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())
Enter fullscreen mode Exit fullscreen mode
== Applied ==
ubuntu: Remove 60-reemote-static.yaml [changed: netplan config /etc/netplan/60-reemote-static.yaml present, will remove]
    $ sudo rm -f /etc/netplan/60-reemote-static.yaml
ubuntu: Remove 60-reemote-lab.yaml [changed: netplan config /etc/netplan/60-reemote-lab.yaml present, will remove]
    $ sudo rm -f /etc/netplan/60-reemote-lab.yaml
ubuntu: Remove 60-reemote-dhcp-lab3.yaml [changed: netplan config /etc/netplan/60-reemote-dhcp-lab3.yaml present, will remove]
    $ sudo rm -f /etc/netplan/60-reemote-dhcp-lab3.yaml
ubuntu: Remove 60-reemote-dhcp-lab4.yaml [changed: netplan config /etc/netplan/60-reemote-dhcp-lab4.yaml present, will remove]
    $ sudo rm -f /etc/netplan/60-reemote-dhcp-lab4.yaml
ubuntu: Remove 60-reemote-vlans.yaml [changed: netplan config /etc/netplan/60-reemote-vlans.yaml present, will remove]
    $ sudo rm -f /etc/netplan/60-reemote-vlans.yaml
Enter fullscreen mode Exit fullscreen mode

Every managed file is present, so every request changes and each one is a single elevated rm -f. A second run reports no change for all five, and an unmanaged file such as the vendor's 50-cloud-init.yaml is never a target. Removing a file does not withdraw its effect from the running stack: to retire a real interface, follow netplan.absent with your own netplan.apply request in the same deploy.

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_netplan_article_examples.py
Enter fullscreen mode Exit fullscreen mode

For the real Ubuntu host, preview every script first, then apply the configuration examples in this order:

uv run python examples/articles/netplan/netplan_hello.py --apply
uv run python examples/articles/netplan/netplan_static_ip.py --apply
uv run python examples/articles/netplan/netplan_rendered.py --apply
uv run python examples/articles/netplan/netplan_dhcp.py --apply
uv run python examples/articles/netplan/netplan_vlan.py --apply
uv run python examples/articles/netplan/netplan_inspect.py --check
Enter fullscreen mode Exit fullscreen mode

Then repeat them. Every command below should report no changes and send no commands:

uv run python examples/articles/netplan/netplan_hello.py --apply
uv run python examples/articles/netplan/netplan_static_ip.py --apply
uv run python examples/articles/netplan/netplan_rendered.py --apply
uv run python examples/articles/netplan/netplan_dhcp.py --apply
uv run python examples/articles/netplan/netplan_vlan.py --apply
Enter fullscreen mode Exit fullscreen mode

netplan_apply_try.py is deliberately absent from both lists: it is stateless, so a second pass reports a change and runs again, which is the correct behaviour for an activation command 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 drop-ins and proving the removal converges:

uv run python examples/articles/netplan/netplan_cleanup.py --apply
uv run python examples/articles/netplan/netplan_cleanup.py --apply
uv run python examples/articles/netplan/netplan_inspect.py
Enter fullscreen mode Exit fullscreen mode

The second netplan_cleanup.py pass reports no change for all five files, and the final inspection lists only the vendor's 50-cloud-init.yaml.

Implementation summary

Reemote's netplan support is four facts and three operations built around one disciplined write. NetplanConfig dumps the merged document — as YAML text, because netplan get speaks no JSON, and a caller who wants a dict parses it — NetplanRenderer answers the backend choice, NetplanFiles lists the drop-ins in merge order, and NetplanFile returns one file's raw text, distinguishing absent, empty and unreadable. All three content reads are two-tier, since a 0600 root-owned file answers a login user with a refusal. netplan.config 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, then installs it in one elevated shell step as root:root mode 0600 and — with validate left on — runs netplan generate so a broken document fails the deploy instead of the boot. netplan.absent removes exactly the named file through the same read-back gate. netplan.apply is stateless by design and always reports a change, as netplan apply or as netplan try --timeout N.

The practical result is a netplan workflow with no templates, no handlers and no YAML library in the base dependency set. A drop-in is a hashable string argument in an ordinary Python function, the preview shows the real host state every decision came from, and a second pass writes nothing for the file operations while the activation step stays explicit and separately scheduled. Sequencing lives in the deploy: yield the writes, then yield the apply, and Reemote runs them in that order across the fleet. The module reference lists the complete API, and the examples index describes the shared real-host execution contract.

References

Netplan background

Top comments (0)