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.
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.
Creating an Inventory File
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. The repository examples use the Ubuntu entries in inventory.json instead, keeping the article's scripts directly runnable against real hosts:
[
{
"host": "ubuntu",
"family": "Ubuntu",
"connection": {
"connector": "ssh",
"address": "192.168.0.127",
"username": "supervisor",
"known_hosts": null,
"key_path": "~/.ssh/id_ed25519"
},
"group": "ubuntu",
"tags": ["ubuntu_host", "apt_package_manager"]
}
]
Replace the documentation address, user and key path with your own. family is required and lets the deploy choose apt rather than dnf or apk. connector may be omitted for SSH because SSH is the default, but spelling it out makes the distinction clear. Verify the host key and populate ~/.ssh/known_hosts rather than disabling host-key checking on a production inventory.
Every entry 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. The connecting user needs passwordless sudo for the elevated examples, or sudo credentials supplied through the inventory's privilege mapping.
Runnable examples for the inventory Ubuntu host
The examples live in the Reemote Git repository: https://github.com/kimjarvis/reemote/tree/main. Clone it after configuring your SSH inventory:
git clone https://github.com/kimjarvis/reemote.git
cd reemote
Replace the cloned repository's inventory.json with your inventory, or edit its Ubuntu entry to match your host. The scripts under examples/articles/linux/ load that file, select only entries whose family is Ubuntu, and use sudo for root-owned state. Mutating scripts preview by default; add --apply only after reviewing the plan. The reboot example additionally requires --confirm-reboot.
| Example | Article concept |
|---|---|
hello.py |
Canonical greeting adapted to real SSH hosts |
commands.py |
Immediate commands with gather_action
|
reboot.py |
Reboot, connection wait and boot-ID polling |
packages.py |
Idempotent and family-aware package installation |
facts.py |
Typed facts and the reboot-required marker |
inventory_data.py |
Host data, group defaults and web-server metadata |
deploy.py |
Dry-run/apply deploy, group guards and host packages |
caddy.py |
Control-side rendering and a change-driven restart |
conditional.py |
Frozen fact and change-outcome conditions |
app_secrets.py |
Control-side SOPS decryption |
smtp.py |
Secret file installation and mode enforcement |
Run a read-only preview from the repository root:
uv run python examples/articles/linux/packages.py
Every Python example is exercised offline by tests/test_linux_article_examples.py; the suite simulates the hosts and never contacts the inventory. The configuration snippets are also parsed and validated there.
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.
commands.py loads the inventory introduced above and gathers uname -r, uptime, and journalctl --no-pager -n 1. It assumes that journalctl is installed on every selected host:
uv run python examples/articles/linux/commands.py
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 reboot.py 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.
The default run only reads the current boot IDs. Rebooting is destructive, so the real action needs both explicit flags:
uv run python examples/articles/linux/reboot.py
uv run python examples/articles/linux/reboot.py --apply --confirm-reboot
WaitForConnection 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. Keep an out-of-band recovery path when rebooting a fleet.
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 installs tmux and vim twice so the second run demonstrates convergence:
uv run python examples/articles/linux/packages.py --apply
uv run python examples/articles/linux/packages.py --apply
The first run installs any missing packages. The second reports [no change: all packages present].
Reemote also provides package operations for DNF and APK. The same script's install_packages deploy chooses the operation from static inventory data. Its 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:
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. facts.py compares the installed Vim version, kernel release, and distribution across the Ubuntu inventory. It calls gather_fact for apt.DebPackage, server.KernelVersion, and server.LinuxName:
uv run python examples/articles/linux/facts.py
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. The same script queries the Ubuntu/Debian /var/run/reboot-required marker with a Shell action:
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.
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_data.py defines host_with_packages, SERVERS, WORKSTATIONS, and INVENTORY. Each entry carries its package tuple alongside the usual connection and group fields. The deploy then reads that tuple instead of embedding it in the operation:
def host_packages(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. inventory_data.py also defines GROUP_PACKAGES and host_with_group_default, plus GROUP_INVENTORY as a complete example.
The precedence rule is explicit: a host-level packages argument wins; otherwise the group default applies. The same pattern works for welcome messages, service ports, or any other static configuration value.
This is ordinary Python rather than a special inheritance language. You can compute defaults, validate them, or load them from another source, and the final inventory still consists of plain dictionaries.
Creating a Deploy
A deploy is a synchronous generator that yields operation requests through op(). deploy.py contains the package deployment and previews it before applying:
uv run python examples/articles/linux/deploy.py
uv run python examples/articles/linux/deploy.py --apply
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.
To restrict a deployment to one group, pass only that group's list to run, or attach a when predicate to each request. deploy.py also provides is_server and server_packages, which attach the stable module-level predicate 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.
Installing Caddy in a Task
The package deploys are intentionally small. A real application usually combines several operations: install a package, write a configuration file, and restart a service when the configuration changes. Caddy makes a compact example because its configuration can be a short text file.
The recommended shape is to render on the control node before the deploy and pass the finished string to files.install. caddy.py does this with render_caddyfile and render_configs; json.dumps quotes the welcome message safely. The rendered dictionary is fixed before either phase, so the requests remain hashable and deterministic.
The same file provides build_caddy(configs) for the package and Caddyfile requests, and build_restart(changed, daemon_reload=False) for the handler. Its main() runs the first deploy, freezes the names of hosts whose notifying operations reported a change, and only then runs the restart deploy:
uv run python examples/articles/linux/caddy.py
uv run python examples/articles/linux/caddy.py --apply
inventory_data.py includes a WEBSERVERS entry with a welcome_message; the runnable script defaults that message to Hello world! for ordinary inventory entries.
The first run installs Caddy and writes /etc/caddy/Caddyfile. The code then freezes the names of hosts whose notifying operations reported a change. build_restart turns that frozen set into a second deploy, so Caddy restarts only on hosts that changed.
This two-deploy split is the key detail. A plain run() deploy cannot branch on the result of an operation it yielded earlier, because its generator runs once against pre-deployment state and again against live state. Reading the ApplyReport between two complete runs moves the decision to a point where the outcome is final and immutable.
The Caddy package must be available from the target's configured repositories. On distributions where it is not, add the vendor repository with Reemote's repository operations before requesting the package, or install a pinned binary with the file operations.
How Does It All Work?
The Caddy example uses more of Reemote's execution model than the earlier scripts, so it is worth stepping back through what run() does.
First, Reemote validates and materializes the inventory. It then executes the deploy generator in a prepare phase. Each yielded operation reads the facts it needs and emits a command descriptor only if the current state differs from the requested state. The resulting plan shows which hosts would change and why.
For a dry run, execution stops there. For a normal run, Reemote executes the generator again in the apply phase and compares the new request sequence with the prepared sequence. If the requests differ, it raises a determinism error rather than applying a plan that no longer matches the code.
Once the sequences match, Reemote applies the operations in order. At each step, eligible hosts run concurrently, and the driver waits for that step to finish before advancing to the next operation. This lockstep execution gives every host the same logical schedule while still overlapping network and command latency across the fleet.
The apply report records each host's outcome: changed, unchanged, or skipped. A non-zero command fails the run rather than being silently recorded as a successful change. At the end, Reemote closes the connections it owns and returns the plan, report, and host objects to the caller.
This model explains several design choices. Request arguments must be hashable and value-stable because they are compared between phases. when predicates must read static inventory data because both phases must make the same eligibility decision. And a decision based on an earlier operation's result belongs between runs, not in an ordinary generator branch.
Conditional Operations
Static conditions belong in when predicates. A deploy that installs a package only on Red Hat family hosts can select dnf.packages and attach a family guard; the earlier family-aware package example showed the selection half.
Conditions based on facts require one more step. Gather the fact before calling run(), freeze the result, and pass it into a deploy factory. conditional.py gathers server.LinuxName, closes its connections, and passes the eligible names to build_debian_deploy:
uv run python examples/articles/linux/conditional.py
The eligible set is fixed before either phase starts, so the branch is deterministic. Do not call gather_fact or read mutable host state from inside an ordinary deploy generator and use the answer to choose which requests to yield.
Conditions based on change outcomes follow the Caddy pattern. conditional.py also exposes changed_from_report(report, notifying), which includes a host if any matching entry changed. Pass the resulting frozen set to caddy.build_restart; the second deploy then stays deterministic across its own prepare and apply phases.
For more complex orchestration, keep explicit fact and change barriers in separate Python steps around run() calls. The ordinary run() path intentionally keeps caller-driven fact barriers and change-outcome branches outside the generator so its two-phase contract stays simple.
Applying GitOps with Reemote
Once the inventory, deploy modules, and configuration content live in files, they can be stored in Git as the authoritative record of the infrastructure. A change becomes a reviewable diff rather than a sequence of commands typed into a terminal.
A practical repository might contain:
inventory.json
deploy.py
tasks/
caddy.py
secrets.json
.sops.yaml
.pre-commit-config.yaml
Pre-commit hooks can check Python syntax, run the test suite, and lint the deployment code. A pull request then shows which packages, files, and services the deployment code manages, and another team member can review that intent before it reaches production.
Continuous integration can add a stronger check by running the deploy against disposable containers or test hosts. A dry run against a representative inventory catches invalid arguments and unresolved inputs without changing a real server. A normal run against a disposable target verifies convergence and can run the deployment a second time to detect unintended changes.
After a pull request is merged, a delivery workflow can install the repository, retrieve the deployment credentials, and run the deploy. This is the GitOps loop: Git holds the desired state, review protects the change, automation applies it, and the next run proves whether the target already matches.
Secrets need separate treatment. Storing encrypted secret material in the same repository preserves the reviewable workflow without committing plaintext passwords.
Using Secrets with Reemote
Reemote does not require a special secrets file format or a global configuration object. Because a deploy is Python, it can call an existing secrets manager before constructing its operations.
One option is Secrets OPerationS (SOPS) with age encryption. Create a .sops.yaml file that selects your age public key, replacing the placeholder below with the key you generated:
creation_rules:
- age: >-
age1ql3zl7d8k4m2p9w6y5x4c3v2b1n0m9a8s7d6f5g4h3j2k
Create an encrypted JSON file with:
sops edit secrets.json
The decrypted document can contain ordinary key-value pairs:
{
"smtp_user": "your-smtp-user",
"smtp_password": "your-smtp-password"
}
After you save and close the editor, SOPS encrypts the values in secrets.json. The encrypted file can be committed to Git; only a holder of the corresponding private key can decrypt it. Running sops edit secrets.json again opens the decrypted content and re-encrypts it when saved.
app_secrets.py provides load_secrets, which runs sops --decrypt --output-type json only when called. Importing the module does not decrypt anything or invoke an external command.
smtp.py renders the finished environment string and passes it to files.install, then uses files.file to enforce mode 0600 even when the content is already correct:
uv run python examples/articles/linux/smtp.py
uv run python examples/articles/linux/smtp.py --apply
The second operation enforces the file mode even when the content is already correct. Reemote logs command descriptors rather than printing the environment file's contents, but you should still avoid logging the secrets mapping or the operation arguments yourself.
This integration has no privileged plugin API. SOPS handles encryption and decryption, Python handles the workflow, and Reemote receives the finished configuration through the same operation used for non-secret files. Keep secrets.json encrypted at rest and never commit the decrypted values.
Test the Examples and Check Convergence
The canonical container example is copied verbatim from the Alpine article and is exercised offline with simulated Docker hosts. The SSH examples select the repository's real Ubuntu inventory entry but pytest substitutes SimulatedHost, so the regular suite opens no network connection.
Run the focused offline checks with:
uv run pytest tests/test_linux_article_examples.py
The tests build and hash every request, run the package and file deploys to convergence in memory, check preview/apply ordering and reboot safeguards, verify fact and action cleanup, and parse the inventory and SOPS configuration snippets. tests/test_examples.py additionally scans every new example for mutable operation arguments and checks sibling imports.
For a live convergence check, preview first and apply only after reviewing the plan:
uv run python examples/articles/linux/packages.py --apply
uv run python examples/articles/linux/packages.py --apply
The first run reports missing packages as changes; the second reports no change. Do not run the reboot or Caddy examples on a production host merely to test the article.
Conclusion
Reemote brings configuration management back to a small set of Python ideas: a list of hosts, generator functions that describe desired state, facts that observe the present state, and an execution model that compares the two. Its immediate actions cover ad-hoc commands, while its state operations make package, file, and service changes idempotent.
The Docker connector is useful for experiments and tests, SSH is the normal path to real machines, and the same inventory and deploy code can move between them. Python remains available for the parts that a configuration language often makes awkward: group defaults, control-side rendering, external secrets, and custom deployment logic.
The documentation covers the complete module vocabulary and the two-phase execution rules. For a fleet that already speaks Python, those are enough building blocks to keep the desired state readable, reviewable, and reproducible.
References
- Reemote documentation: https://reemote.org/
- Source: https://github.com/kimjarvis/reemote/tree/main
- Install:
pip install reemote(Python 3.13+) - License: EPL-2.0
- Discord: https://discord.gg/de8MqzA3E
Top comments (0)