Ansible is the canonical configuration management tool. Ansible relies on two core principles: dry run — check for changes before you apply them — and lockstep execution, where each operation completes on all hosts before the next one starts. The Reemote library implements Ansible's core principles in Python. Reemote is a pure Python library for configuration management that is very similar to Ansible.
Let's look at an example that demonstrates both dry run and lockstep execution in Reemote.
Try it in under a minute (docker connector)
Reemote ships a docker connector that runs your deploy inside a local container, so you need neither a remote host nor an SSH key to see the two principles work. Docker or Podman must be installed locally — the connector shells out to whichever CLI you name in the inventory, and there is no default. Two steps:
# 1. Install (Python 3.13+; pip works just as well as uv) uv venv .venv && source .venv/bin/activate && uv pip install reemote # 2. Save the script below as hello.py, then run it python hello.py The inventory holds two hosts and the deploy has two steps, so the run demonstrates lockstep as well as dry run: the first step has to finish on both hosts before the second step starts on either.
# hello.py import asyncio from reemote import files, format_log, format_plan, op, run INVENTORY = [ { "host": "web1", "family": "Alpine", "connection": { "connector": "docker", "identifier": "alpine:3.20", "docker_cmd": "podman", # or "docker" }, }, { "host": "web2", "family": "Alpine", "connection": { "connector": "docker", "identifier": "alpine:3.20", "docker_cmd": "podman", # or "docker" }, }, ] def deploy(host): # Step 1: create the demo directory on every host. yield op(files.directory, name="Create the demo directory", path="/tmp/reemote-demo", mode="0755") # Step 2: write a greeting into it -- runs only after step 1 has # finished on every host. yield op(files.install, name="Write a greeting", content="Hello from reemote!\n", dest="/tmp/reemote-demo/hello.txt", mode="0644") async def main(): # Dry run: facts are gathered for real, nothing is mutated. plans, _, _ = await run(INVENTORY, deploy, dry=True) print("== Dry run: what would change ==") print(format_plan(plans)) # Apply: the same deploy, executed against fresh containers. _, report, _ = await run(INVENTORY, deploy) print("\n== Applied: what changed ==") assert report is not None print(format_log(report)) asyncio.run(main()) Reemote starts a throwaway alpine:3.20 container per host, previews both steps against both containers without touching them, then runs the same deploy for real against a second pair of containers, prints the resulting command log, and finally commits each container into a new image and removes it. Verified output:
== Dry run: what would change == web1: Create the demo directory [changed: /tmp/reemote-demo missing, will create] web1: Write a greeting [changed: content /tmp/reemote-demo/hello.txt is absent, will install] web2: Create the demo directory [changed: /tmp/reemote-demo missing, will create] web2: Write a greeting [changed: content /tmp/reemote-demo/hello.txt is absent, will install] == Applied: what changed == web1: Create the demo directory [changed: /tmp/reemote-demo missing, will create] $ mkdir -p /tmp/reemote-demo $ chmod 755 /tmp/reemote-demo web2: Create the demo directory [changed: /tmp/reemote-demo missing, will create] $ mkdir -p /tmp/reemote-demo $ chmod 755 /tmp/reemote-demo web1: Write a greeting [changed: content /tmp/reemote-demo/hello.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-00b39035d25048db/content $ sh -c 'mkdir -p /tmp/reemote-demo && cp /tmp/reemote-install-00b39035d25048db/content /tmp/reemote-demo/hello.txt && chmod 644 /tmp/reemote-demo/hello.txt && rm -rf /tmp/reemote-install-00b39035d25048db' web2: Write a greeting [changed: content /tmp/reemote-demo/hello.txt is absent, will install] $ scp <files install> -> /tmp/reemote-install-00b39035d25048db/content $ sh -c 'mkdir -p /tmp/reemote-demo && cp /tmp/reemote-install-00b39035d25048db/content /tmp/reemote-demo/hello.txt && chmod 644 /tmp/reemote-demo/hello.txt && rm -rf /tmp/reemote-install-00b39035d25048db' Every dry-run line reappears in the apply log verbatim, with the shell commands appended beneath it — that is the point. The plan the dry run showed you is the plan the apply executed. Each run(...) starts its own throwaway containers from alpine:3.20, so both phases observe the same empty state; the demo is about the two principles, not idempotence.
Look closely, though, and the two blocks are ordered differently. The dry-run plan is host-major: web1's two steps, then web2's two. The apply log is step-major: step 1 on both hosts, then step 2 on both. Same four lines, two orders — and the apply log's order is lockstep execution made visible. Both hosts create the directory before either host writes the greeting. The rest of this article is about how each of those two orderings is produced.
The inventory is a plain Python list of host dictionaries carrying connection information. Reemote is agentless: for SSH targets the connection block configures an asyncssh connection.
A deploy is a generator that yields operation requests in order — here, a files.directory then a files.install. In general these operations map closely to their Ansible counterparts, so the vocabulary will be familiar.
The following deploy installs and starts nginx:
def deploy(host): yield op(apt.packages, name="Install nginx", packages=("nginx",), sudo=True) yield op(files.install, name="Write landing page", content=PAGE, dest="/var/www/html/index.html", mode="0644", sudo=True) yield op(systemd.service, name="Run nginx", service="nginx", running=True, enabled=True, sudo=True) Point that deploy at your staging inventory with dry=True first and you get a per-host, per-operation diff of what staging is about to look like — the packages that will be installed, the file that will change, the service that will be started or left alone — before any of it happens. Read it, then run the same code without dry=True to apply.
The program is asynchronous. Operations are dispatched to every host in the inventory concurrently, and the controller waits for every host to finish an operation before advancing to the next.
run(...) returns the plans and the report as structured objects your program can inspect, so the dry-run diff is not just printable text — it is data you can gate a rollout on, log to a dashboard, or attach to a pull request.
How dry run is implemented
"Every dry-run line reappears in the apply log verbatim." That is easy to promise and surprisingly hard to earn, so it is worth being precise about what makes it true.
The problem
A configuration change against production is scary, and the usual antidotes are weak. Echoing the shell commands you think you would run shows your intent, not the effect on a host whose real state you never read. A separate "check mode" bolted onto a tool is a second code path that drifts from the one that actually applies, so the preview lies in exactly the edge cases you hoped it would catch. What you want is a guarantee: the thing you previewed and the thing you executed are computed by the same code, against the same live facts, and differ only in whether the final commands get sent.
Why it is interesting
Reemote earns the "same line" property structurally, not by discipline. There is no separate dry-run implementation to keep in sync, because a dry run is not a different mode — it is the first half of the ordinary run, stopped before it sends anything.
The solution
run(inventory, deploy, dry=True) validates the inventory, materializes a Host per entry, and calls run_prepare(hosts, deploy, planning=dry). When dry is set it returns (plans, None, hosts) and never calls run_apply at all. The None in the report slot is why the example guards with assert report is not None before printing format_log(report): a dry run produces a plan, not a log.
The prepare phase is where the guarantee lives. For each host, _prepare_host:
- Creates a per-host, per-phase
FactCachetaggedphase="prepare". - Drains the deploy generator into a list of
OperationRequestobjects. A counter tallies everyop(...)the body built against every one it actually yielded, so a body that forgets ayieldfails here — before anything is sent — with aDeployRequestErrornaming the host. - For each request, calls
materialize(...)and records aPlannedOperation(request, changed, reason, commands). A request whosewhenguard fails on this host is recordedskippedwithout reading a single fact — a guard exists precisely to keep an inapplicable operation off a host that could not even answer its facts.
Operations are generators, and materializing one never sends a command. An operation is an async generator function; materialize drives it to completion and collects what it yields:
ctx = OpContext(host=host, facts=cache, planning=planning) commands = [cmd async for cmd in request.func(ctx, *request.args, **request.kwargs)] return ctx, commands Running the generator reads facts and builds command descriptors; it does not execute them. The descriptors are collected into a tuple and returned. Nothing in the prepare path calls send_command — that happens only later, inside run_apply. So a dry run genuinely touches the host (facts are gathered over the wire) but genuinely mutates nothing.
Facts are cached and compared — that is where changed comes from. An operation reads current state through ctx.facts.get(FactClass, *args). FactCache.get memoizes on (fact_cls, args, sorted kwargs), and on a miss it awaits fact_cls.process(host, ...) — a coroutine, because a fact gathers its value by running shell commands over asyncssh (or through the docker connector's overridden transport). Facts are typed data, never scraped strings: FileExists.process runs test -e, re-asking elevated when a parent directory denies the login user traversal; FileContents.process cats a file, falling back to an elevated read for a mode the login user cannot open.
The operation compares the fact it read against the state it wants and sets ctx.changed and ctx.reason itself. This is "check for changes before apply" expressed as ordinary Python. Here is the real decision inside files.install:
current = await ctx.facts.get(FileContents, dest) if current == content: ctx.reason = f"content already up to date ({dest})" return # no change -> yields no commands ctx.changed = True ctx.reason = (f"content {dest} differs, will install" if current is not None else f"content {dest} is absent, will install") yield InstallSpoolCommand(content=content, dest=spool) # the scp line yield InstallCommand(spool=spool, dest=dest, mode=mode_int, ...) # the sh -c line On a fresh alpine:3.20 container /tmp/reemote-demo/hello.txt does not exist, so FileContents reads back None, the comparison fails, and the operation sets reason="content /tmp/reemote-demo/hello.txt is absent, will install" and yields two descriptors. That reason string is the exact text in the example's dry-run line, and those two descriptors are the exact scp and sh -c lines under it in the apply log. They are the same strings because they are produced by the same materialize call — run once in prepare, once in apply.
The one place the two runs differ is the planning flag threaded onto OpContext (set from dry). A full run keeps its prepare strict: an operation whose input does not exist yet raises, so a typo fails before a single command is sent. A dry=True prepare runs in planning mode, which lets an operation whose input a later request of the same deploy would create — a spool a subsequent step extracts, say — report a plan line instead of raising on state that has not been produced yet.
Changes are reported as data, then rendered. Each PlannedOperation carries changed, reason and the commands tuple. format_plan renders one line per operation — host: name [changed|no change|skipped: reason] — and deliberately omits the $ command lines; those belong to format_log, which renders the apply-phase report. But the plan is not only text: run returns it as dict[str, list[PlannedOperation]], structured objects you can assert on.
What follows from the solution
In the example,
run(INVENTORY, deploy, dry=True)starts a throwaway container per host, reads/tmp/reemote-demo(absent) and/tmp/reemote-demo/hello.txt(absent) as real facts over the connector, records both steps as[changed]forweb1andweb2, sends nothing, commits and removes both containers, and returns the plans withreport=None.format_planprints the four lines host-major — each host's two steps together — because it walksplans.items(), one host at a time.
Because a dry run is the prepare phase of the real run, the preview cannot drift from the apply: same materialize, same operations, same reason strings. The plan line reappears verbatim as the apply log's entry line, with the commands it built appended beneath it.
Because the plan is a returned value, you can gate on it: assert in CI that no host reports changed, attach the diff to a pull request, or refuse a rollout when a host you expected to be clean is not.
The catch is that a dry run is only as faithful as the deploy is deterministic. The driver re-invokes the generator for the apply phase and compares each pulled request against the plan; branch on a live fact, or build a fresh value per pass (datetime.now(), random, an inline lambda), and the two sequences diverge — which raises DeterminismError before anything is sent. Dry run does not just tolerate pure, functional deploys; it rewards them, and the determinism guard enforces them.
How lockstep execution is implemented
The dry-run plan walked each host's work in turn. The apply log did the opposite: it ran step 1 on both hosts, then step 2 on both. That step-major ordering is not a rendering choice — it is the shape of the execution, and it comes from a single join.
The problem
With N hosts across a network you want two things that pull in opposite directions. You want concurrency: the network wait for host A should overlap the wait for host B, not run after it. And you want cross-host ordering: operation i finishes everywhere before operation i+1 starts anywhere. Some deploys depend on that ordering — a repository before the package it provides, a schema migration before the app that reads the new column, a directory before the file that lands in it.
The naive answers each give up one of the two. "One task per host, let them race" gets concurrency but loses ordering: a fast host is writing the config file while a slow one is still installing the package. "One host at a time, top to bottom" gets ordering but throws away concurrency and runs the fleet serially.
Why it is interesting
The resolution has to hold under real networks, where hosts finish the same operation at wildly different times. The barrier cannot be "wait a moment"; it has to be "wait for every host, whoever is slowest, before anyone advances."
The solution
run_apply(runtimes, plans) keeps a list of active hosts and loops in three steps:
active = [rt for rt in runtimes if not rt.done] while active: # Step 1 -- pull the next request from every active host (synchronous). for rt in active: rt.fact_cache = FactCache(rt.host, phase="apply") # fresh per step item = next(rt.generator) # StopIteration -> rt.done rt.current_request = item # ... compare each pulled request against the plan; DeterminismError on drift ... # Step 2 -- execute this step on all active hosts at once. The gather join # IS the barrier: no host pulls request i+1 until every step-i has returned. results = await asyncio.gather( *(_apply_host_step(rt) for rt in active), return_exceptions=True ) # ... append log entries; aggregate PrivilegeError; re-raise anything else ... # Step 3 -- drop finished hosts. active = [rt for rt in active if not rt.done] Operations are async, and the concurrency is only across hosts. Inside _apply_host_step, the request is re-materialized against the fresh cache and — only when ctx.changed is true — its commands are sent sequentially:
ctx, commands = await materialize(rt.host, rt.fact_cache, request) if ctx.changed: for cmd in commands: await send_command(rt.host, cmd, sudo=sudo, su=su, doas=doas, env=request.env) So a single host's commands stay in order (some sequences are order-dependent), while asyncio.gather overlaps the hosts. The gather's join is the barrier: the loop cannot reach step 1 of the next iteration — cannot pull request i+1 for anyone — until every _apply_host_step coroutine for step i has returned. An operation is an async-generator function (materialize refuses anything else with OperationError); facts await asyncssh; send_command is a coroutine. The deploy script itself stays a plain synchronous generator — you never write async in a deploy. All the asynchrony lives in the runtime.
asyncssh is the wire. A real Host owns a lazily-established asyncssh connection, and send_command dispatches each descriptor by kind: a TransferCommand copies over the connection's scp channel (cmd.transfer), a WaitCommand polls a fact (cmd.wait), and anything else runs its shell through host.run_shell or, when elevated, host.run_shell_privileged. The docker connector is the same Host with the transport seams overridden — connect, _run_shell, upload_file, download_file, aclose — to shell out to docker/podman instead, which is why the identical driver code produces the example's mkdir/scp/sh -c lines against a local container.
Connectivity errors are thrown — and aggregated. Because a step's hosts connect concurrently, several can fail at once, and reporting only the first is useless when you need to fix all of them. run_prepare gathers with return_exceptions=True, collects each host's HostConnectionError, and raises HostConnectionError.aggregate(...) naming every unreachable host together. run_apply does the same for PrivilegeError, so one bad sudo_password is reported across the whole fleet at once. A non-zero command exit is different: it raises CommandError and propagates fail-fast, aborting the run rather than reporting a broken step as applied.
What follows from the solution
In the example, read the apply log straight down the page:
web1: Create the demo directory ... (step 1) web2: Create the demo directory ... (step 1) web1: Write a greeting ... (step 2) web2: Write a greeting ... (step 2)
web1andweb2run step 1 concurrently; the gather join holds step 2 until both have returned, so neither host writes the greeting until both have created the directory. The log listsweb1beforeweb2within each step not becauseweb1ran first — they overlapped — but becauseasyncio.gatherreturns results in input order. That is the whole fleet advancing one operation at a time, made visible.
Two further properties fall out of the same loop:
- Deterministic logs.
asyncio.gatherpreserves input order, so the report reads the same way every run regardless of the order hosts finish on the wire. Determinism is a property of the schedule, not of the network. - "Act, then read" within a host. The
FactCacheis rebuilt at every step, so a generator-body fact read sees the effect of the operations before it. Step 2'sfiles.installobserves the directory step 1 created because the cache it reads through is fresh for step 2. Re-materializing also means each step re-checks its governing fact against current state, so a host that converged between plan and apply reports[no change]and sends nothing.
Because every host finishes step i before step i+1, the ApplyReport is a consistent per-step view of the fleet — which is what makes handlers possible without a notify keyword. Read the entries whose changed is true (changed_hosts) and drive a second deploy that restarts a service on exactly those hosts.
The trade is explicit: the slowest host in a step gates the fleet's advance to the next. That is the same bargain Ansible's default linear strategy strikes — a little latency bought back as a schedule you can reason about, one operation at a time, across every host at once.
Summary
Ansible's two core principles are not features bolted onto Reemote; they fall out of one execution model.
A dry run is simply the prepare phase of the ordinary run, stopped before it sends anything. Operations are async generators that read cached facts and compare them against the state you described, so changed and its reason are computed by the same code whether you preview or apply. The plan line and the apply-log line are the same line because they are the same string, produced by the same materialize call — there is no second implementation free to drift.
Lockstep is a single asyncio.gather join in the apply loop. Every host runs its Nth operation concurrently, and the join holds the fleet until the slowest host returns before anyone pulls operation N+1: concurrency across hosts, sequence within a host, and a deterministic log because gather preserves input order. That is why the apply log reads step-major — one operation across all hosts, then the next — while the plan reads host-major. The same loop rebuilds each host's fact cache every step, so an operation re-checks the world as it now is, and a connectivity or privilege failure is aggregated across the fleet rather than surfacing one host at a time.
The result behaves like Ansible — preview before apply, one operation across all hosts at a time — but hands back its plans and reports as ordinary Python objects you can assert on, gate a rollout on, or feed into a second deploy. If you have ever wanted configuration management that shows you the change before it makes it, in the same language as the rest of your stack, Reemote is worth a look.
Try it
- Documentation and full guide: https://reemote.org/
- Source: https://github.com/kimjarvis/reemote
- PyPI:
pip install reemote - License: EPL-2.0