WireGuard is a small, fast VPN protocol that runs in the Linux kernel. A tunnel is described by a handful of lines — an interface address, a UDP port, and one peer block per endpoint holding a public key, the networks it may use and its keepalive — and wg-quick brings that description up as an ordinary network interface. There is no daemon to coordinate with and no central server: two hosts that each know the other's public key can talk the moment both configurations exist.

Tailscale builds a full mesh of WireGuard peers on top of that primitive and removes the parts most operators would rather not run. A coordination service hands out stable 100.x addresses and MagicDNS names, keeps each node's public key current, and rotates it for you; tailscale up joins a network, tailscale set changes what a node advertises, and tailscale status --json reports what the node actually is doing. The WireGuard keys and routes still exist underneath, but the control plane that used to require a public endpoint, a handshake you initiate by hand and a shared secrets file is handled for you.

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 tailscale and wireguard modules are written in that spirit: they read node state, reconcile it against what you asked for, and issue the smallest command that closes the gap. Neither needs an agent, an interpreter or a template file on the managed machine — only the VPN tooling the host already has, plus a POSIX shell and an SSH connection.

This article builds a set of examples that install Tailscale, join a tailnet, turn a node into a subnet router, read the whole fleet's state back, and stand up a raw WireGuard interface, 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 Tailscale and WireGuard relate

The two modules in this article are two views of one thing. WireGuard is the tunnel: a kernel data plane, a wg userspace tool and a wg-quick@<iface> service unit, configured by a file under /etc/wireguard. Tailscale is a managed mesh that speaks WireGuard to the kernel but keeps the keys, the 100.x addressing and the NAT traversal in a tailscaled daemon you drive with the tailscale command. The How Tailscale works write-up and the WireGuard concept page describe exactly that layering.

You rarely run both on the same interface. A tailnet is usually the right default because it removes the coordination the protocol does not define — you point a node at your network and it joins. A hand-written WireGuard interface earns its keep when you want a single site-to-site link with no control plane, a fixed peer whose key you will pin yourself, or an interface that must come up even when the coordination service is unreachable. This article treats them as the two ends of that choice and shows each in Python, without wading into which is better; the references at the end collect the comparison material for anyone deciding.

What matters to automation is that both are converging, stateful systems with a way to read the truth back: tailscale status --json and wg show answer the question "what is this node actually doing", and a correct tool asks that before it issues a command. The --advertise-exit-node, PrivateKey and MagicDNS details differ between the two, but the reconciliation discipline is the same, and it is the discipline Reemote's modules encode.

The Reemote tailscale module

The tailscale module reconciles a node's membership and preferences; it deliberately does not install the software. Its four facts read through the same two-tier probe — the plain command first, then the escalation tool from the inventory when the login user is refused — because tailscale status --json can require root to answer completely:

  • TailscaleStatus parses the backend state, the online flag, the tailnet name and this node's MagicDNS name out of tailscale status --json.
  • TailscaleIPs returns the IPv4 and IPv6 addresses the tailnet assigned to this node.
  • TailscalePrefs reads tailscale debug prefs --json and normalises the advertised routes and the accept/exit/SSH flags into the shape configure_node compares against.
  • TailscalePeerCount is simply the size of the daemon's peer inventory, online or not.

Its four operations each own one decision. tailscale.ensure_authenticated reads the status and, only when the backend is not Running, transfers the auth key to a private /tmp spool, runs tailscale up --authkey=file:… and removes the spool — the key never appears in a plan, a log or a rendered command. tailscale.configure_node reconciles advertised routes and the runtime flags with a single tailscale set holding only the options that actually differ, and refuses to run until the node is authenticated. tailscale.ensure_connection_state brings the node up or down on its own, so an installed, authenticated node sitting tailscale down is repaired with one tailscale up. tailscale.configure_ip_forwarding makes the kernel forward the traffic a subnet router advertises, reconciling the running sysctl values.

Two boundaries carry through the examples. The module installs nothing: pair it with apt (or dnf/apk) for the tailscale package and with systemd for the tailscaled unit. And it does not persist subnet routes across a reboot for you: configure_ip_forwarding is runtime state, and durable forwarding is a sysctl setting request composed into the same deploy.

The Reemote wireguard module

The wireguard module manages the raw interface directly. WireguardConfig dumps a whole wg show <iface> conf answer, WireguardInterfaces lists the interfaces up on the host, WireguardPeers enumerates a given interface's peers, WireguardPublicKey returns the interface's own public key, and WireguardServiceState reports the wg-quick@<iface> unit's running and boot state.

The operations sequence a tunnel: wireguard.install_wireguard makes the userspace tools present, choosing the package manager on the target; wireguard.ensure_keypair writes the interface's private key once, at <key_dir>/<iface>.key mode 0600, and never replaces a key that already exists; wireguard.configure_interface owns <iface>.conf, rendering the interface address and each WireguardPeerConfig into a secret-free template that is uploaded and then installed by an elevated step which reads the target's own private key and publishes the finished file; wireguard.sync_peers and wireguard.manage_service add and remove live peers and drive the unit.

The privacy property is the one worth stating plainly: because the uploaded template carries the placeholder PrivateKey = @REEMOTE_PRIVATE_KEY@ and the substitution happens on the host, no private key ever crosses to the controller or lands in a plan. configure_interface only changes when the rendered text differs from WireguardConfig's read-back, so a stable interface sends nothing.

Inventory for the tailscale and WireGuard 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 request touches root-owned state — the package database, tailscaled, the spooled auth key, /etc/wireguard — 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:

ssh supervisor@192.168.0.251 'tailscale status; ls -l /etc/wireguard 2>/dev/null; sysctl net.ipv4.ip_forward' 

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/tailscale/ 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, tailscale_article_common.py, which holds the package, unit and path constants and the preview/apply driver.

Example Article concept
tailscale_hello.py The canonical two operations against persistent SSH hosts
tailscale_install.py Install the tailscale package and run tailscaled
tailscale_connect.py Authenticate a node with a spooled key and connect it
tailscale_subnet_router.py Advertise a subnet route and enable kernel forwarding
tailscale_inspect.py Read the tailnet and WireGuard facts back for the whole fleet
wireguard_tunnel.py Bring up a raw wg0 interface with keys, a peer and a unit

Run a read-only preview from the repository root:

uv run python examples/articles/tailscale/tailscale_install.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.

# tailscale_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 tailscale_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. 

Install Tailscale and bring up its daemon

Installing a daemon is ordinary package and service work, so it is composed from the modules that already own those jobs rather than a dedicated installer: the apt module installs the tailscale package and the systemd module starts and enables its tailscaled unit. When the host's default sources do not carry tailscale, add the vendor signing key (apt.key) and repository (apt.repo) as two requests ahead of apt.packages; that fetch touches the network, so it is shown by the module reference rather than run by the offline suite. The two requests below are the whole install, and everything the later examples depend on rests on them: an installed package and a running, enabled daemon.

# tailscale_install.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Install the Tailscale package and start its daemon on Ubuntu hosts. Installing a daemon is ordinary package and service work, so it is composed from the modules that already own those jobs rather than a dedicated installer. The ``apt`` module installs the ``tailscale`` package and the ``systemd`` module brings up its ``tailscaled`` unit and enables it at boot. This example keeps the two requests that carry the state the article's later examples depend on: the installed package and a running, enabled daemon. When the host's default sources do not carry ``tailscale``, add the vendor signing key and repository ahead of the package; the composition is two extra requests before ``apt.packages``, shown here rather than run because a repository fetch touches the network the offline test suite must avoid:: yield op(apt.key, name="Add the Tailscale signing key", src=KEY_URL, sudo=True) yield op( apt.repo, name="Add the Tailscale APT repository", src="deb https://pkgs.tailscale.com/stable/ubuntu noble main", filename="tailscale-stable", sudo=True, ) Everything else is what the two requests below already do: install the package if it is absent, then make sure the daemon is running and starts at boot. Running the script again sends nothing, because both facts report the wanted state. Run it with:: uv run python examples/articles/tailscale/tailscale_install.py uv run python examples/articles/tailscale/tailscale_install.py --apply """ import asyncio import sys from pathlib import Path from reemote import apt, op, systemd sys.path.insert(0, str(Path(__file__).resolve().parent)) from tailscale_article_common import ( TAILSCALE_PACKAGE, TAILSCALED_UNIT, execute, is_ubuntu, load_inventory, parser, ) def deploy(host): yield op( apt.packages, name="Install the Tailscale package", packages=(TAILSCALE_PACKAGE,), sudo=True, when=is_ubuntu, ) yield op( systemd.service, name="Run the Tailscale daemon", service=TAILSCALED_UNIT, running=True, 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 preview names each gap it found: one missing package, and a daemon that is neither running nor enabled at boot.

== Preview == ubuntu: Install the Tailscale package [changed: 1 package(s) to install] ubuntu: Run the Tailscale daemon [changed: tailscaled.service not running (None), will start; tailscaled.service not enabled, will enable] Preview only; pass --apply to change the hosts. 

The apply expands those two requests into three commands — one apt-get install, then a start and an enable:

== Applied == ubuntu: Install the Tailscale package [changed: 1 package(s) to install] $ sudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" install tailscale ubuntu: Run the Tailscale daemon [changed: tailscaled.service not running (None), will start; tailscaled.service not enabled, will enable] $ sudo systemctl start tailscaled.service $ sudo systemctl enable tailscaled.service 

Running it again sends nothing, because both the package fact and the unit facts now report the wanted state:

== Preview == ubuntu: Install the Tailscale package [no change: all packages present] ubuntu: Run the Tailscale daemon [no change: tailscaled.service already running; tailscaled.service already enabled] == Applied == ubuntu: Install the Tailscale package [no change: all packages present] ubuntu: Run the Tailscale daemon [no change: tailscaled.service already running; tailscaled.service already enabled] 

Join the tailnet from an auth key

Two operations do the whole join: tailscale.ensure_authenticated and tailscale.ensure_connection_state. The auth key is read from the controller's environment so it never sits in the deploy source:

export TAILSCALE_AUTH_KEY=tskey-auth-... 

The first request transfers that key to a private, mode-0600 spool named after its own hash and runs tailscale up --authkey=file:… --hostname=ubuntu, removing the spool whether the login succeeds or fails; the key appears in no plan and no log. The second reconciles the connected state on its own, so a node that is installed and authenticated but sitting tailscale down comes back with a single tailscale up.

# tailscale_connect.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Join a tailnet: authenticate a node and bring its connection up. Two operations do the whole job. ``tailscale.ensure_authenticated`` reads the node status and, only when the daemon is not already running, transfers the auth key to a private temporary file, runs ``tailscale up --authkey=file:...`` and removes the spool. The key never appears in a plan, a log or a rendered command. ``tailscale.ensure_connection_state`` then reconciles the connected state on its own, so a node that is installed and authenticated but sitting ``tailscale down`` is brought back with a single ``tailscale up``. Read the auth key from the controller environment so it stays out of the deploy source:: export TAILSCALE_AUTH_KEY=tskey-auth-... Re-running the script on a connected node sends nothing: the first operation is a no-op once the backend state is ``Running``, and the second agrees the node is already connected. The node is assumed to have Tailscale installed and ``tailscaled`` running, which ``tailscale_install.py`` arranges. Run it with:: uv run python examples/articles/tailscale/tailscale_connect.py TAILSCALE_AUTH_KEY=tskey-auth-... uv run python examples/articles/tailscale/tailscale_connect.py --apply """ import asyncio import os import sys from pathlib import Path from reemote import op, tailscale sys.path.insert(0, str(Path(__file__).resolve().parent)) from tailscale_article_common import execute, is_ubuntu, load_inventory, parser def deploy(host): yield op( tailscale.ensure_authenticated, name="Authenticate the Tailscale node", auth_key=os.environ.get("TAILSCALE_AUTH_KEY"), hostname=host.name, sudo=True, when=is_ubuntu, ) yield op( tailscale.ensure_connection_state, name="Connect the Tailscale node", present=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()) 

On a node that has never joined, both requests report work — the backend is Stopped, so it must authenticate, and a stopped node must be brought up:

== Preview == ubuntu: Authenticate the Tailscale node [changed: Tailscale state is Stopped, will authenticate with the supplied key] ubuntu: Connect the Tailscale node [changed: Tailscale is Stopped, will up] Preview only; pass --apply to change the hosts. 

The apply transfers the key out of sight and authenticates. Because the daemon's own up finishes the join, the second request sees the node already connected and adds nothing — that observation is the point: later operations read the state earlier ones produced.

== Applied == ubuntu: Authenticate the Tailscale node [changed: Tailscale state is Stopped, will authenticate with the supplied key] $ scp <tailscale auth key> -> /tmp/reemote-tailscale-auth-969c6b7c5e6f2482/authkey $ sudo sh -c 'tailscale up --authkey=file:/tmp/reemote-tailscale-auth-969c6b7c5e6f2482/authkey --hostname=ubuntu; rc=$?; rm -rf -- /tmp/reemote-tailscale-auth-969c6b7c5e6f2482; exit $rc' ubuntu: Connect the Tailscale node [no change: Tailscale already connected] 

Run against the now-connected node, both requests are no-ops and the spool is gone:

== Preview == ubuntu: Authenticate the Tailscale node [no change: Tailscale is already authenticated and running] ubuntu: Connect the Tailscale node [no change: Tailscale already connected] == Applied == ubuntu: Authenticate the Tailscale node [no change: Tailscale is already authenticated and running] ubuntu: Connect the Tailscale node [no change: Tailscale already connected] 

Advertise a subnet route

A subnet router does two independent jobs, and the module keeps them separate. tailscale.configure_node reconciles the node's advertised routes with a single tailscale set, comparing each requested preference against TailscalePrefs first, and tailscale.configure_ip_forwarding makes sure the kernel will actually forward the traffic. The node must already be authenticated — configure_node refuses to run when the backend state is not Running, which the join above gets it there. Routes such as 192.0.2.0/24 are documentation values from the reserved example range; replace them with your subnet and enable it in the admin console before it carries traffic.

# tailscale_subnet_router.py # Copyright (c) 2026 Kim Jarvis. # SPDX-License-Identifier: EPL-2.0 """Turn a node into a subnet router that advertises a route to the tailnet. A subnet router does two independent jobs, and the module keeps them separate. ``tailscale.configure_node`` reconciles the node's advertised routes with a single ``tailscale set``, comparing each requested preference against ``TailscalePrefs`` first so a router already advertising the route is left untouched. ``tailscale.configure_ip_forwarding`` then makes sure the Linux kernel will actually forward the traffic, reconciling the running ``sysctl`` values only. Persisting forwarding across a reboot is the ``sysctl`` module's job, composed in the deploy as two ``sysctl.setting`` requests writing ``/etc/sysctl.d/99-tailscale.conf``; it is left out here so the example changes only runtime state it can safely converge, exactly as the router needs when the host already carries the drop-in. The node must already be authenticated — ``configure_node`` refuses to run when the backend state is not ``Running``, and ``tailscale_connect.py`` gets it there. Routes such as ``192.0.2.0/24`` are documentation examples from the reserved example range; replace them with the subnet your tailnet manages, and enable it in the admin console before the routes carry traffic. Run it with:: uv run python examples/articles/tailscale/tailscale_subnet_router.py uv run python examples/articles/tailscale/tailscale_subnet_router.py --apply """ import asyncio import sys from pathlib import Path from reemote import op, tailscale Source:https://dev.to/kimbofab/how-to-use-tailscale-and-wireguard-to-configure-vpns-in-python-2bon

Related posts