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:
-
TailscaleStatusparses the backend state, the online flag, the tailnet name and this node's MagicDNS name out oftailscale status --json. -
TailscaleIPsreturns the IPv4 and IPv6 addresses the tailnet assigned to this node. -
TailscalePrefsreadstailscale debug prefs --jsonand normalises the advertised routes and the accept/exit/SSH flags into the shapeconfigure_nodecompares against. -
TailscalePeerCountis 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
sys.path.insert(0, str(Path(__file__).resolve().parent))
from tailscale_article_common import execute, is_ubuntu, load_inventory, parser
# The subnet this node advertises to the rest of the tailnet.
ADVERTISED_ROUTES = ("192.0.2.0/24",)
def deploy(host):
yield op(
tailscale.configure_node,
name="Advertise the subnet route",
advertise_routes=ADVERTISED_ROUTES,
accept_routes=True,
sudo=True,
when=is_ubuntu,
)
yield op(
tailscale.configure_ip_forwarding,
name="Enable kernel forwarding",
advertise_routes=ADVERTISED_ROUTES,
ipv6=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 freshly joined router, one tailscale set writes the two differing preferences, and two sysctl -w calls turn on the running forwarders:
== Applied ==
ubuntu: Advertise the subnet route [changed: Tailscale preferences differ (advertise_routes, accept_routes), will update]
$ sudo tailscale set --advertise-routes=192.0.2.0/24 --accept-routes=true
ubuntu: Enable kernel forwarding [changed: IP forwarding disabled (net.ipv4.ip_forward, net.ipv6.conf.all.forwarding), will enable]
$ sudo sysctl -w net.ipv4.ip_forward=1
$ sudo sysctl -w net.ipv6.conf.all.forwarding=1
Re-run against the same host and both requests find the preferences and the sysctls already match, so nothing is sent:
== Preview ==
ubuntu: Advertise the subnet route [no change: Tailscale preferences already match the requested values]
ubuntu: Enable kernel forwarding [no change: IPv4 and requested IPv6 forwarding already enabled]
== Applied ==
ubuntu: Advertise the subnet route [no change: Tailscale preferences already match the requested values]
ubuntu: Enable kernel forwarding [no change: IPv4 and requested IPv6 forwarding already enabled]
Bring up a raw WireGuard interface
The wireguard module is the hands-on counterpart to the managed tailnet: the same wg/wg-quick tooling Tailscale builds on, driven directly. Four requests sequence the whole tunnel — install the tools, generate the keypair once, render and install wg0.conf, then start and enable wg-quick@wg0. Because the uploaded template carries only a placeholder, the private key is read on the host during install and never reaches the controller. The addresses and peer key below are documentation values; replace Endpoint with a reachable peer.
# wireguard_tunnel.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Bring up a raw WireGuard interface with wg-quick, keys and a peer.
This is the hands-on counterpart to the managed tailnet: the ``wireguard``
module drives the same ``wg``/``wg-quick`` tooling Tailscale builds on, so the
pieces below are what a Tailscale node is doing underneath. Four operations
sequence the whole 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 ``/etc/wireguard/wg0.key`` with mode ``0600``, and never
replaces a key that already exists. ``wireguard.configure_interface`` owns
``wg0.conf``: it renders the interface address and each ``WireguardPeerConfig``
into a secret-free template, uploads that, and lets an elevated install read the
target's own private key and publish the finished file — so no key material ever
crosses to the controller or lands in a plan. ``wireguard.manage_service`` starts
``wg-quick@wg0`` and enables it at boot.
The addresses and peer key are documentation values from the reserved ranges;
replace ``Endpoint`` with a reachable peer. On a second run every operation
compares its fact and sends nothing, because the tools, the key, the configuration
and the unit all already match.
Run it with::
uv run python examples/articles/tailscale/wireguard_tunnel.py
uv run python examples/articles/tailscale/wireguard_tunnel.py --apply
"""
import asyncio
import sys
from pathlib import Path
from reemote import op, wireguard
sys.path.insert(0, str(Path(__file__).resolve().parent))
from tailscale_article_common import (
WG_INTERFACE,
WG_KEY_DIR,
execute,
is_ubuntu,
load_inventory,
parser,
)
# The tunnel's own addressing and its single peer. The public key, endpoint and
# allowed IPs are documentation values; the interface address is a /24 from the
# private range the tunnel routes over.
WG_ADDRESS = "10.8.0.1/24"
WG_LISTEN_PORT = 51820
WG_PEERS = (
wireguard.WireguardPeerConfig(
public_key="aK0B0k2Zl9t0m4exampleQ7rS5n1Yd3Xg8Pc6Vb0Lm2k=",
allowed_ips=("10.8.0.2/32",),
endpoint="203.0.113.5:51820",
persistent_keepalive=25,
),
)
def deploy(host):
yield op(
wireguard.install_wireguard,
name="Install the WireGuard tools",
sudo=True,
when=is_ubuntu,
)
yield op(
wireguard.ensure_keypair,
name="Create the wg0 keypair",
interface=WG_INTERFACE,
key_dir=WG_KEY_DIR,
sudo=True,
when=is_ubuntu,
)
yield op(
wireguard.configure_interface,
name="Configure the wg0 interface",
interface=WG_INTERFACE,
address=WG_ADDRESS,
listen_port=WG_LISTEN_PORT,
peers=WG_PEERS,
key_dir=WG_KEY_DIR,
sudo=True,
when=is_ubuntu,
)
yield op(
wireguard.manage_service,
name="Start and enable wg-quick@wg0",
interface=WG_INTERFACE,
enabled=True,
running=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 reports each missing piece — no tools, no key, no config, an inactive unit:
== Preview ==
ubuntu: Install the WireGuard tools [changed: WireGuard tools not installed, will install]
ubuntu: Create the wg0 keypair [changed: /etc/wireguard/wg0.key absent, will generate]
ubuntu: Configure the wg0 interface [changed: /etc/wireguard/wg0.conf absent or differs, will install]
ubuntu: Start and enable wg-quick@wg0 [changed: wg0 inactive, will start; wg0 boot state differs, will enable]
Preview only; pass --apply to change the hosts.
The apply is the whole bring-up. Note the config step: an unprivileged upload of the secret-free template, then one elevated shell that validates the private key, substitutes it into a freshly written wg0.conf at mode 0600, and removes the spool:
== Applied ==
ubuntu: Install the WireGuard tools [changed: WireGuard tools not installed, will install]
$ sudo sh -c 'if command -v apt-get >/dev/null 2>&1; then apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y wireguard wireguard-tools; elif command -v dnf >/dev/null 2>&1; then dnf install -y wireguard-tools; elif command -v apk >/dev/null 2>&1; then apk add --no-cache wireguard-tools; else exit 127; fi'
ubuntu: Create the wg0 keypair [changed: /etc/wireguard/wg0.key absent, will generate]
$ sudo sh -c 'mkdir -p /etc/wireguard && umask 077 && tmp=$(mktemp /etc/wireguard/.wg0.key.XXXXXX) || exit 1; trap '"'"'rm -f -- "$tmp"'"'"' EXIT HUP INT TERM; wg genkey > "$tmp" && chown 0:0 "$tmp" && chmod 0600 "$tmp" || exit 1; if ln -- "$tmp" /etc/wireguard/wg0.key; then :; elif [ -e /etc/wireguard/wg0.key ] || [ -L /etc/wireguard/wg0.key ]; then :; else exit 1; fi'
ubuntu: Configure the wg0 interface [changed: /etc/wireguard/wg0.conf absent or differs, will install]
$ scp <wireguard config> -> /tmp/reemote-wireguard-5e5182fa7c84b374/interface.conf
$ sudo sh -c 'umask 077; key=$(cat -- /etc/wireguard/wg0.key) || exit 1; printf '"'"'%s\n'"'"' "$key" | wg pubkey >/dev/null 2>&1 || { printf '"'"'Invalid WireGuard private key\n'"'"' >&2; exit 1; }; mkdir -p /etc/wireguard && tmp=$(mktemp /etc/wireguard/.wg0.conf.XXXXXX) || exit 1; trap '"'"'rm -f -- "$tmp"'"'"' EXIT; trap '"'"'exit 1'"'"' HUP INT TERM; count=0; while IFS= read -r line; do if [ "$line" = '"'"'PrivateKey = @REEMOTE_PRIVATE_KEY@'"'"' ]; then count=$((count + 1)); printf '"'"'PrivateKey = %s\n'"'"' "$key" || exit 1; else printf '"'"'%s\n'"'"' "$line" || exit 1; fi; done < /tmp/reemote-wireguard-5e5182fa7c84b374/interface.conf > "$tmp" || exit 1; [ "$count" -eq 1 ] || exit 1; chown root:root "$tmp" && chmod 0600 "$tmp" && mv -f -- "$tmp" /etc/wireguard/wg0.conf && rm -rf -- /tmp/reemote-wireguard-5e5182fa7c84b374'
ubuntu: Start and enable wg-quick@wg0 [changed: wg0 inactive, will start; wg0 boot state differs, will enable]
$ sudo systemctl start wg-quick@wg0.service
$ sudo systemctl enable wg-quick@wg0.service
A second run sends nothing: the tools, the key, the rendered config and the unit all compare equal to their facts.
== Preview ==
ubuntu: Install the WireGuard tools [no change: WireGuard tools already installed]
ubuntu: Create the wg0 keypair [no change: /etc/wireguard/wg0.key keypair already exists with secure metadata]
ubuntu: Configure the wg0 interface [no change: /etc/wireguard/wg0.conf already up to date]
ubuntu: Start and enable wg-quick@wg0 [no change: wg0 already active; wg0 already enabled]
== Applied ==
ubuntu: Install the WireGuard tools [no change: WireGuard tools already installed]
ubuntu: Create the wg0 keypair [no change: /etc/wireguard/wg0.key keypair already exists with secure metadata]
ubuntu: Configure the wg0 interface [no change: /etc/wireguard/wg0.conf already up to date]
ubuntu: Start and enable wg-quick@wg0 [no change: wg0 already active; wg0 already enabled]
Read the tailnet state back
The last script mutates nothing. It gathers the facts both modules offer and prints one JSON object per host, so an operator sees the same values the write operations compared against. Every fact reads through the same two-tier probe, so an elevated tailscale status --json answers even when the login user cannot run it. Pass --check to exit nonzero until each host reports the tailnet Running — the readiness gate between a node being installed and usable.
# tailscale_inspect.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0
"""Read back the tailnet and WireGuard state a fleet is actually in.
This script mutates nothing. It gathers the facts the two modules offer and prints
one JSON object per host, so an operator can see the same values the write
operations compared against:
* ``TailscaleStatus`` — backend state, online flag, tailnet name and this node's
MagicDNS name;
* ``TailscaleIPs`` — the IPv4 and IPv6 addresses the tailnet assigned;
* ``TailscalePrefs`` — advertised routes and the accept/exit/SSH flags, which is
what ``configure_node`` reconciles against;
* ``TailscalePeerCount`` — how many peers the daemon currently knows;
* ``WireguardInterfaces`` — the raw ``wg`` interfaces up on the host.
Every fact reads through the same two-tier probe the operations use, so an
elevated ``tailscale status --json`` answers even when the login user cannot run
it. Pass ``--check`` to exit nonzero until each host reports the tailnet
``Running`` — the readiness gate between a node being installed and usable.
Run it with::
uv run python examples/articles/tailscale/tailscale_inspect.py
uv run python examples/articles/tailscale/tailscale_inspect.py --check
"""
import asyncio
import json
import sys
from pathlib import Path
from reemote import (
Host,
TailscaleIPs,
TailscalePeerCount,
TailscalePrefs,
TailscaleStatus,
WireguardInterfaces,
gather_fact,
)
sys.path.insert(0, str(Path(__file__).resolve().parent))
from tailscale_article_common import load_inventory, parser
async def collect(hosts):
"""Gather the tailscale and wireguard facts and align them per host."""
statuses = await gather_fact(hosts, TailscaleStatus, sudo=True)
ips = await gather_fact(hosts, TailscaleIPs, sudo=True)
prefs = await gather_fact(hosts, TailscalePrefs, sudo=True)
peers = await gather_fact(hosts, TailscalePeerCount, sudo=True)
interfaces = await gather_fact(hosts, WireguardInterfaces, sudo=True)
rows = {}
for host in hosts:
status = statuses[host.name]
rows[host.name] = {
"backend_state": status["backend_state"],
"online": status["online"],
"tailnet": status["current_tailnet"],
"dns_name": status["self_dns_name"],
"tailscale_ips": ips[host.name],
"advertise_routes": prefs[host.name]["advertise_routes"],
"accept_routes": prefs[host.name]["accept_routes"],
"ssh_enabled": prefs[host.name]["ssh_enabled"],
"peer_count": peers[host.name],
"wireguard_interfaces": interfaces[host.name],
}
return rows
def tailnets_are_up(rows):
"""Whether every host reports the Tailscale backend as Running."""
return all(row["backend_state"] == "Running" 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 host reports the tailnet as Running",
)
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(json.dumps(row, indent=2))
if args.check:
if not tailnets_are_up(rows):
down = [name for name, row in rows.items() if row["backend_state"] != "Running"]
print(f"tailnet not up on: {', '.join(down)}")
raise SystemExit(1)
print("every host reports the tailnet as Running")
return rows
if __name__ == "__main__":
asyncio.run(main())
After the join and the subnet router have run, the readiness check prints the reconciled view and exits zero:
== ubuntu ==
{
"backend_state": "Running",
"online": true,
"tailnet": "example.ts.net",
"dns_name": "ubuntu.example.ts.net",
"tailscale_ips": [
"100.64.0.1",
"fd7a:115c:a1e0::1"
],
"advertise_routes": [
"192.0.2.0/24"
],
"accept_routes": true,
"ssh_enabled": false,
"peer_count": 2,
"wireguard_interfaces": [
"wg0"
]
}
every host reports the tailnet as Running
On a node that has not joined yet the same script prints the same object with backend_state Stopped and exits 1 — that nonzero exit is what a CI gate or a chained && acts on.
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_tailscale_article_examples.py
For the real Ubuntu host, preview every script first, then apply the configuration examples in this order:
uv run python examples/articles/tailscale/tailscale_hello.py --apply
uv run python examples/articles/tailscale/tailscale_install.py --apply
uv run python examples/articles/tailscale/wireguard_tunnel.py --apply
uv run python examples/articles/tailscale/tailscale_inspect.py
Then repeat them. Every command below should report no changes and send no commands:
uv run python examples/articles/tailscale/tailscale_hello.py --apply
uv run python examples/articles/tailscale/tailscale_install.py --apply
uv run python examples/articles/tailscale/wireguard_tunnel.py --apply
tailscale_connect.py and tailscale_subnet_router.py are deliberately absent from both lists: joining a tailnet authenticates against your real coordination server and advertising a route changes traffic the shared host forwards, so neither is safe to replay unattended on a machine you are logged into. Preview them, and apply them only against a tailnet and subnet you control. Finish by reading the state back:
uv run python examples/articles/tailscale/tailscale_inspect.py
The second pass of each listed script reports no change and issues no commands, which is exactly the convergence the transcripts above demonstrate against the simulated host.
Implementation summary
Reemote's VPN support is two modules over one reconciliation rule: read the node's real state, and issue the smallest command that closes a genuine gap. The tailscale module is four facts (TailscaleStatus, TailscaleIPs, TailscalePrefs, TailscalePeerCount) over tailscale status --json and tailscale debug prefs --json, and four operations — ensure_authenticated, configure_node, ensure_connection_state and configure_ip_forwarding — that install nothing and never leak an auth key, spooling it to a private file that is removed whatever the exit code. The wireguard module is five facts over wg show and the unit state, and operations that generate a keypair once, render a secret-free wg.conf template, and let an elevated on-host step substitute the private key so it never crosses to the controller. Installation and durable forwarding are composed from apt, systemd and sysctl, because those modules already own them.
The practical result is a VPN workflow with no templates, no handlers and no agent on the target. A deploy is an ordinary Python generator; the preview shows the real host state every decision came from; a second pass sends nothing for the reconciling operations while ensure_connection_state stays explicit. Sequencing lives in the deploy — yield the install requests, then the join, then the route — and Reemote runs them in order across the fleet, with later operations observing the state earlier ones produced. The module references list the complete API, and the examples index describes the shared real-host execution contract.
References
Tailscale and WireGuard background
- How Tailscale works
- The WireGuard concept in Tailscale
- Tailscale compared to WireGuard
- WireGuard vs Tailscale (Contabo)
- Tailscale vs WireGuard (Kunal Ganglani)
Reemote documentation: https://reemote.org/
Install:
pip install reemote(Python 3.13+)License: EPL-2.0
Discord: https://discord.gg/de8MqzA3E
Top comments (0)