Keeping Linux machines in a known state requires a configuration management system. Reemote approaches that problem as a Python library: your inventory, deployment logic, and integrations are ordinary Python code, while Reemote supplies the facts, idempotent operations, and execution model that turn that code into changes on remote machines.

If you already know Python, the learning curve is short. Loops, conditions, functions, classes, and third-party packages are all available without translating your intent into a separate configuration language. Under the hood, Reemote renders Python operations as shell commands and transfers them over SSH. The target needs a POSIX-compatible shell, but it does not need Python or a Reemote agent.

Reemote is a younger project than the established configuration management systems, so its built-in module collection and surrounding ecosystem are smaller. That is the trade-off for a compact, Python-native design. When an operation is missing, the answer is often a small Python function rather than a new plugin system.

The examples below progress from a disposable container to a reusable inventory, a multi-step application deployment, and a GitOps workflow. They use Python 3.13 or newer and run on Reemote 0.1.4 as well as current source.

Installing Reemote

Reemote is a Python package, so install it with pip or the more modern uv package manager. A virtual environment keeps the project dependencies separate from other Python work:

python3 -m venv .venv . .venv/bin/activate python -m pip install reemote 

With uv, the equivalent setup is:

uv venv . .venv/bin/activate uv pip install reemote 

Confirm that the package imports and shows its version:

python -c 'import reemote; from importlib.metadata import version; print(version("reemote"))' 

The examples assume that the commands run from the directory containing your inventory and deploy files.

A Docker Base Example

The quickest way to see Reemote work is to target a local container. The Docker connector accepts either an existing container or an image name. When given an image, it creates a throwaway container for each run, so the example can install a file without leaving a changed container behind.

Save the following as hello.py:

# hello.py import asyncio from reemote import files, format_log, format_plan, op, run INVENTORY = [{ "host": "demo", "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") async def main(): plans, _, _ = await run(INVENTORY, deploy, dry=True) print("== Dry run ==") print(format_plan(plans)) _, report, _ = await run(INVENTORY, deploy) print("\n== Apply ==") assert report is not None print(format_log(report)) asyncio.run(main()) 

Replace podman with docker if that is the container runtime you use. Run the script with:

python hello.py 

The output has two parts:

== Dry run == demo: Write a greeting [changed: content /tmp/reemote-hello.txt is absent, will install] == Apply == demo: 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' 

The files.install operation first transfers the content to a temporary spool file, then installs it with an elevated shell command when necessary. This spool-and-install pattern lets Reemote write root-owned files without embedding arbitrary file content directly in a privileged shell command.

The container example also illustrates an important connector detail: an image-based Docker host owns its container. Closing it commits the result to a new image and removes the container. Separate dry-run and apply calls therefore both begin from the original image rather than from the state left by the preceding call.

Inventory, Operations, and Facts

The container inventory introduces the three central Reemote concepts: inventory, operations, and facts.

An inventory is a Python list of dictionaries. Each dictionary describes one host, including its name, operating-system family, connection settings, and optional metadata. The family value is one of Ubuntu, RedHat, or Alpine; it lets deployment code choose the appropriate package manager without first discovering the distribution.

Reemote separates immediate actions from state operations. An action executes a command now, such as uname -r. A state operation describes the desired state and is idempotent: it compares that state with the current state and changes something only when the two differ.

Facts are read-only observations of a host. Operations use facts to decide whether a command is necessary. For example, a package operation reads the installed-package state and requests an installation only when the package is absent.

The distinction is practical. A shell command is appropriate for a one-off query or an intentionally non-idempotent action. A state operation is usually the better choice for configuration because a second run converges to the same result without repeating work that is already complete.

Running Commands in Python

The hello.py script used a state operation. For an immediate command, Reemote provides actions such as Shell. The gather_action helper runs an action concurrently across a list of hosts and returns a dictionary keyed by host name.

The following script assumes an inventory named INVENTORY, which the "Creating an Inventory File" section below shows how to create. It also assumes that journalctl is installed on every selected host:

# commands.py import asyncio from reemote import Host, Shell, gather_action from inventory import INVENTORY hosts = [Host.from_inventory(entry) for entry in INVENTORY] async def main(): for command in ("uname -r", "uptime", "journalctl --no-pager -n 1"): results = await gather_action(hosts, Shell, command=command) print(f"$ {command}") for name, result in results.items(): print(f"{name}: {result['stdout'].strip()}") asyncio.run(main()) 

Each Shell result contains exit_status, stdout, and stderr. A non-zero command exit is data returned to the caller; connection, timeout, and privilege failures are reported as typed exceptions.

gather_action closes the host connections it used when the call returns. The same Host objects can be reused for later calls; each call opens and closes a fresh connection.

On a systemd host with journalctl installed, a command such as journalctl --follow works too, but it never finishes under normal circumstances, so the call waits until you interrupt it or the command exits. Reemote captures the result rather than maintaining an interactive terminal session.

Rebooting and Checking Uptime

The same action API can reboot a host and then wait for it to return. A reboot normally drops the SSH connection before the command can return a clean result, so the script treats that specific connection loss as expected. It records the boot ID beforehand, then polls until the machine has a new boot ID and reports its uptime. Checking the boot ID avoids a race in which SSH briefly accepts a connection while the old system is still shutting down.

# reboot.py import asyncio from reemote import ( Host, HostConnectionError, Shell, WaitForConnection, gather_action, ) from inventory import INVENTORY async def main(): hosts = [Host.from_inventory(entry) for entry in INVENTORY] before = await gather_action( hosts, Shell, command="cat /proc/sys/kernel/random/boot_id", ) old_boot_ids = { name: result["stdout"].strip() for name, result in before.items() } try: await gather_action(hosts, Shell, command="reboot", sudo=True) except HostConnectionError as exc: # A successful reboot can tear down SSH connections mid-command. print(f"Reboot disconnected a host: {exc}") hosts = [Host.from_inventory(entry) for entry in INVENTORY] await gather_action(hosts, WaitForConnection, timeout=300, retry=5) async with asyncio.timeout(300): while True: try: result = await gather_action( hosts, Shell, command="cat /proc/sys/kernel/random/boot_id && uptime", ) except HostConnectionError: # SSH can disappear again while the old systems shut down. await asyncio.sleep(5) continue lines = { name: output["stdout"].strip().splitlines() for name, output in result.items() } if all(lines[name][0] != old_boot_ids[name] for name in old_boot_ids): for name, output in lines.items(): print(f"{name}: {output[1]}") return await asyncio.sleep(5) asyncio.run(main()) 

The WaitForConnection action polls until the host is reachable or the timeout expires. The boot-ID loop then waits for every host to complete its reboot, and each final uptime reports the time since that host's new boot.

The reboot and package examples use sudo=True; the connecting user must therefore have passwordless sudo, or sudo credentials must be supplied through the inventory's privilege mapping.

Installing Packages Idempotently

A package installation is a better fit for a state operation than a shell command. The apt.packages operation reads the installed-package facts, installs only missing packages, and reports no change when the desired set is already present.

# packages.py import asyncio from reemote import apt, format_log, op, run from inventory import INVENTORY def deploy(host): yield op(apt.packages, name="Install tmux and vim", packages=("tmux", "vim"), sudo=True) async def main(): for attempt in (1, 2): _, report, _ = await run(INVENTORY, deploy) print(f"== Run {attempt} ==") assert report is not None print(format_log(report)) asyncio.run(main()) 

On an Ubuntu or Debian host, the first run installs any missing packages. The second run ends with:

== Run 2 == demo: Install tmux and vim [no change: all packages present] 

Reemote also provides package operations for DNF and APK. A family-aware deploy can choose the operation from static inventory data. The small host_family helper works with published Reemote 0.1.4, which preserves family in host.extra, and with current source, which exposes host.family:

from reemote import apt, apk, dnf, op def host_family(host): return getattr(host, "family", None) or host.extra["family"] def install_packages(host): installer = { "Ubuntu": apt.packages, "RedHat": dnf.packages, "Alpine": apk.packages, }[host_family(host)] yield op(installer, name="Install tmux and vim", packages=("tmux", "vim"), sudo=True) 

This branch is safe because the family value is fixed for both execution phases. It does not depend on a fact that could change while the deploy is running.

Getting Facts from Your Servers

The package operation already used facts internally, but you can gather the same read-only information directly. Suppose you want to compare the installed Vim version and kernel release across several Ubuntu machines. Materialize the inventory and call gather_fact for each fact:

# facts.py import asyncio from reemote import Host, apt, gather_fact, server from inventory import INVENTORY async def main(): hosts = [Host.from_inventory(entry) for entry in INVENTORY] try: vim = await gather_fact(hosts, apt.DebPackage, "vim") kernels = await gather_fact(hosts, server.KernelVersion) distributions = await gather_fact(hosts, server.LinuxName) finally: await asyncio.gather(*(host.aclose() for host in hosts)) for name in vim: package = vim[name] version = package["version"] if package else "not installed" print(f"{name}: {distributions[name]}, kernel {kernels[name]}, " f"vim {version}") asyncio.run(main()) 

gather_fact returns one value per host and runs the reads concurrently. Unlike gather_action, it does not close the connections it opens, so the script closes them in a finally block.

Reemote does not currently provide a distribution-neutral RebootRequired fact. On Ubuntu and Debian, the conventional /var/run/reboot-required marker can be queried with a Shell action instead:

results = await gather_action( hosts, Shell, command="if [ -f /var/run/reboot-required ]; then echo yes; else echo no; fi", ) 

Treat that marker as an operating-system-specific convention, not as a portable fact. The module documentation lists the facts that are available for each subsystem.

Creating an Inventory File

The Docker example kept its inventory inline. For a real fleet, a separate inventory.py makes the targets and their metadata easier to reuse. The file is ordinary Python, so groups can be lists that are combined into the final inventory.

# inventory.py SSH = { "username": "your-user", "key_path": "~/.ssh/id_ed25519", } def host(name, group): return { "host": name, "family": "Ubuntu", "connection": dict(SSH, address=name), "group": group, "tags": [group], } SERVERS = [ host("podpile.home", "servers"), host("microos.home", "servers"), host("code.example.com", "servers"), ] WORKSTATIONS = [ host("nov.home", "workstations"), host("tux.home", "workstations"), ] INVENTORY = SERVERS + WORKSTATIONS 

Every entry in these inventories supplies host, family, and connection; current Reemote requires all three. The group and tags fields are optional classifiers that deployment code can inspect. Additional keys are preserved in host.extra, which provides a simple place for host-specific data.

To restrict a deployment to one group, pass only that group's list to run, or attach a when predicate to each request. A predicate must remain stable across the prepare and apply phases, so define it at module level:

def is_server(host): return host.group == "servers" def deploy(host): yield op(apt.packages, name="Install tmux and vim", packages=("tmux", "vim"), sudo=True, when=is_server) 

The when guard keeps the request in every host's schedule but skips it on ineligible hosts. That uniform schedule lets Reemote compare hosts in lockstep without losing determinism.

Creating a Deploy

A deploy is a synchronous generator that yields operation requests through op(). Put the package deployment in deploy.py:

# deploy.py import asyncio from reemote import apt, format_log, format_plan, op, run from inventory import INVENTORY def deploy(host): yield op(apt.packages, name="Install packages", packages=("tmux", "vim"), sudo=True) async def main(): plans, _, _ = await run(INVENTORY, deploy, dry=True) print(format_plan(plans)) _, report, _ = await run(INVENTORY, deploy) assert report is not None print(format_log(report)) asyncio.run(main()) 

The dry run reads the current state for real and plans the work without applying changes. The normal run performs the same preparation, checks that the request sequence is unchanged, and then applies the plan. This gives you a reviewable preview without maintaining a second description of the deployment.

Use tuples rather than lists for operation arguments such as packages. Requests must be hashable and comparable by value so that Reemote can verify that both phases describe the same work.

Using Host Data

A single package list is rarely ideal for every machine. Reemote preserves additional inventory keys in host.extra, so the inventory can carry a package list for each host and the deploy can remain generic.

# inventory.py SSH = { "username": "your-user", "key_path": "~/.ssh/id_ed25519", } def host(name, group, packages): return { "host": name, "family": "Ubuntu", "connection": dict(SSH, address=name), "group": group, "tags": [group], "packages": tuple(packages), } SERVERS = [ host("podpile.home", "servers", ("tmux", "vim")), host("microos.home", "servers", ("tmux",)), host("code.example.com", "servers", ("tmux", "vim")), ] WORKSTATIONS = [ host("nov.home", "workstations", ("git", "tmux", "vim")), host("tux.home", "workstations", ("git",)), ] INVENTORY = SERVERS + WORKSTATIONS 

The deploy now reads the list from the host instead of embedding it in the operation:

def deploy(host): yield op(apt.packages, name="Install host packages", packages=host.extra["packages"], sudo=True) 

The inventory remains data, while the deploy remains reusable. Because the package tuple is fixed before the run starts, both execution phases see the same value.

Using Group Data

Host data is flexible, but repeating the same package list for every member of a group defeats the purpose of grouping. A small inventory helper can provide group defaults and allow individual hosts to override them.

# inventory.py SSH = { "username": "your-user", "key_path": "~/.ssh/id_ed25519", } GROUP_PACKAGES = { "servers": ("tmux", "vim"), "workstations": ("git", "tmux", "vim"), } def host(name, group, packages=None, **extra): data Source:https://dev.to/kimbofab/managing-systems-and-applications-with-reemote-31a4

Related posts