Manage Rust on servers with Python
Cargo is Rust's package manager and build tool: it resolves dependencies, compiles crates and installs command-line programs. Rustup manages Rust toolchains, including the compiler, standard library, targets and components.
Reemote is a pure-Python configuration-management library that brings the two together on real servers: your inventory and deployment logic are ordinary Python, while Reemote gathers typed facts, previews changes, and applies idempotent operations over SSH or a container connector.
This article starts with the canonical two-container quickstart, then builds persistent, real-host examples: the barrier-aware rustup role installs Rust from each distribution's own repositories, the rustup module adds a WebAssembly target to an existing toolchain, the cargo module installs the command-line crates ripgrep, fd-find and bat, and the last example compiles and runs a Rust program that invokes those three binaries.
Every script previews the plan before it applies anything, and the stateful ones are rerun to confirm convergence.
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.
The canonical quickstart uses disposable Alpine containers to demonstrate Reemote's execution model. The rest of this article targets persistent Ubuntu and RedHat servers over SSH, where Rust is installed and the same operations can be rerun to prove convergence.
Meet Rust on a server
Rust has three pieces worth distinguishing. rustc compiles source code. Cargo builds Cargo projects, fetches their dependencies and installs standalone crates with cargo install. Rustup manages named toolchains and their targets and components.
A crate is the package unit: it can be a library used by a Cargo project or a program that Cargo installs as a binary. That last distinction matters here. The examples install command-line crates globally, then compile a small Rust program that invokes those installed binaries. They do not pretend that a global cargo install makes library crates available to an unrelated rustc command.
The rustup role provisions Rust from the distribution's own repositories. On Ubuntu it installs the rustup package, selects the stable toolchain and can install Cargo crates. On RedHat it installs the AppStream rust, cargo, rustfmt and clippy packages instead, because Enterprise Linux does not provide a rustup RPM. Alpine is outside this role's supported family set.
The role is barrier-aware. Reemote plans an entire wave before applying it, so toolchain and crate requests cannot be planned before the package install has provided rustup or cargo. A FileExists fact closes the package wave; only when that binary exists does the next wave plan the toolchain and crate operations. The role therefore runs with run_waves, not the request-only run driver.
Inventory for SSH connections to Rust hosts
The examples use the real Ubuntu and RedHat hosts in the repository inventory. The relevant entries look like this:
[
{
"host": "web1",
"family": "RedHat",
"connection": {
"address": "192.168.0.101",
"username": "supervisor",
"key_path": "~/.ssh/id_ed25519"
},
"group": "centos",
"tags": ["web"]
},
{
"host": "web2",
"family": "RedHat",
"connection": {
"address": "192.168.0.224",
"username": "supervisor",
"key_path": "~/.ssh/id_ed25519"
},
"group": "centos",
"tags": ["web"]
},
{
"host": "ubuntu",
"family": "Ubuntu",
"connection": {
"address": "192.168.0.251",
"username": "supervisor",
"key_path": "~/.ssh/id_ed25519"
},
"group": "ubuntu",
"tags": ["ubuntu_host", "apt_package_manager"]
}
]
Replace those addresses, user names and key paths with your own hosts. family selects the role's package-manager branch. The package requests elevate with sudo=True; toolchain, target and crate requests run as the connecting user so they read and modify that user's ~/.rustup and ~/.cargo trees. Passwordless sudo must therefore be available for the connecting account.
Keep SSH host-key verification enabled. Omitting known_hosts makes Reemote use AsyncSSH's normal verification against the connecting user's known-hosts files, normally including ~/.ssh/known_hosts.
Before using --apply, obtain each server's host-key fingerprint through a trusted channel, such as its provider console or the command ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub run on the server. Then connect with ssh supervisor@192.168.0.101 and compare the fingerprint shown at the prompt with that trusted value before accepting the key. Repeat for every host. Never treat unverified ssh-keyscan output as proof of identity.
If you use a custom known-hosts file, set connection.known_hosts to its path; do not set it to null, which disables verification. The shared example loader also removes legacy known_hosts: null entries in memory before connecting.
Runnable examples for the Rust inventory hosts
The runnable scripts live at https://github.com/kimjarvis/reemote/tree/main/examples/articles/rust/. Like the Alpine examples, they load the repository's real inventory.json, select only Ubuntu and RedHat entries, and preview by default. Add --apply only after reviewing the plan.
hello.py- Canonical preview/apply deploy against the real SSH hostsinstall_rust.py- The barrier-aware rustup role and its resolved variablesextend_rustup.py- Add a target with the rustup moduleinstall_crates.py- Install command-line crates with the cargo modulerun_program.py- Compile and run a Rust program that uses the installed crates
Clone the repository, put your inventory in its root, and start with a read-only preview:
git clone https://github.com/kimjarvis/reemote.git
cd reemote
uv run python examples/articles/rust/hello.py
hello.py is the SSH counterpart of the canonical container example. It writes only two small files under /tmp, so it is a safe first check of the inventory and transport.
Install Rust with the rustup role
The role packages the complete provisioning sequence. RustupVars carries its inputs: build requirements, distribution packages, the default toolchain and Cargo crates. The example overrides only cargo_crates, installing ripgrep now and leaving fd-find and bat for the Cargo module example.
Save this as install_rust.py:
# install_rust.py
import asyncio
import sys
from pathlib import Path
from reemote import resolve_vars
from reemote.roles import RustupVars, rustup
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
from rust_article_common import INVENTORY, execute_waves, parse_apply_flag
__all__ = ["INVENTORY", "build_deploy", "main"]
OVERRIDES = {"cargo_crates": ("ripgrep",)}
def build_deploy():
"""Resolve the role variables before any host is contacted."""
vars_set = resolve_vars(RustupVars, "rustup", INVENTORY, overrides=OVERRIDES)
return rustup(vars_set)
async def main() -> None:
await execute_waves(build_deploy, apply_changes=parse_apply_flag(__doc__))
if __name__ == "__main__":
asyncio.run(main())
resolve_vars validates the role inputs before any connection opens. The returned rustup(vars_set) is a deploy factory for run_waves. On Ubuntu the waves install requirements and the rustup package, cross the binary barrier, select stable, then install ripgrep. On RedHat they install requirements and AppStream's compiler packages, cross the equivalent cargo barrier, then install ripgrep; there is no rustup toolchain request.
Run the preview first, then apply it explicitly:
uv run python examples/articles/rust/install_rust.py
uv run python examples/articles/rust/install_rust.py --apply
uv run python examples/articles/rust/install_rust.py --apply
The final run is the convergence check: installed packages, the Ubuntu default toolchain and the crate should all report no change.
Extend the toolchain with the rustup module
The rustup module controls an existing rustup installation. Its facts report installed toolchains, the default, targets and components. Its operations reconcile those states: install or remove toolchains, choose a default, and add or remove targets or components.
The next example adds the wasm32-unknown-unknown target to Ubuntu's stable toolchain. The target is useful when the same source will also be compiled for WebAssembly. The family guard is deliberate: the RedHat hosts in this inventory have Cargo and rustc from AppStream, but no rustup binary to query.
Save this as extend_rustup.py:
# extend_rustup.py
import asyncio
import sys
from collections.abc import Generator
from pathlib import Path
from reemote import Host, OperationRequest, op, rustup
_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
sys.path.insert(0, str(_HERE))
from rust_article_common import INVENTORY, execute, parse_apply_flag
__all__ = ["INVENTORY", "deploy", "main"]
TARGETS = ("wasm32-unknown-unknown",)
def deploy(host: Host) -> Generator[OperationRequest]:
"""Only Ubuntu has rustup in this inventory; RedHat uses distro packages."""
if host.family == "Ubuntu":
yield op(
rustup.targets,
name="Add WebAssembly target",
targets=TARGETS,
toolchain="stable",
)
async def main() -> None:
await execute(deploy, apply_changes=parse_apply_flag(__doc__))
if __name__ == "__main__":
asyncio.run(main())
rustup.targets first reads rustup +stable target list --installed. It emits rustup +stable target add wasm32-unknown-unknown only when the target is missing, so rerunning the same request converges. The request stays unprivileged because the target belongs to the connecting user's toolchain.
uv run python examples/articles/rust/extend_rustup.py --apply
uv run python examples/articles/rust/extend_rustup.py --apply
Install command-line crates with the cargo module
The cargo module manages crates installed globally with cargo install. Its package fact parses Cargo's installe
Comments
No comments yet. Start the discussion.