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 

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

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"] } ] 

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' 

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/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 

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()) 

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. 

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()) 

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. 

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 

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)] 

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, routesSource:https://dev.to/kimbofab/how-to-use-python-and-netplan-to-configure-static-ip-addresses-3fnl

Related posts