# 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.

```bash
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.

```python
# 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.

```text
== 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](../roles/rustup.md) 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:

```json
[
  {
    "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.

| Example | Article concept |
| --- | --- |
| [`hello.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/rust/hello.py) | Canonical preview/apply deploy against the real SSH hosts |
| [`install_rust.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/rust/install_rust.py) | The barrier-aware `rustup` role and its resolved variables |
| [`extend_rustup.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/rust/extend_rustup.py) | Add a target with the `rustup` module |
| [`install_crates.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/rust/install_crates.py) | Install command-line crates with the `cargo` module |
| [`run_program.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/rust/run_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:

```bash
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`:

```python
# 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:

```bash
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](../modules/rustup.md) 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`:

```python
# 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.

```bash
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](../modules/cargo.md) manages crates installed globally with `cargo install`. Its package fact parses Cargo's installed-crate listing, and `cargo.packages` compares that state with the requested crates before installing, upgrading or removing anything. Bare names are accepted, as are Reemote's `<crate>=<version>` pins and wildcard pins.

This example installs two more command-line crates: `fd-find`, whose Cargo-installed binary is named `fd`, and `bat`, a syntax-aware file viewer. Together with `ripgrep` from the role, they give the final program three real tools to invoke.

Save this as `install_crates.py`:

```python
# install_crates.py
import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, cargo, op

_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"]

CRATES = ("fd-find", "bat")


def deploy(host: Host) -> Generator[OperationRequest]:
    """Install into the connecting user's Cargo home, without elevation."""
    yield op(
        cargo.packages,
        name="Install fd-find and bat",
        packages=CRATES,
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())
```

No `sudo` is needed: Cargo's registry, build cache and installed binaries belong to the connecting user. The operation reads that same user's `cargo install --list`, so elevating only the command would make the fact and the mutation disagree.

```bash
uv run python examples/articles/rust/install_crates.py --apply
uv run python examples/articles/rust/install_crates.py --apply
```

## Compile and run a Rust program on the host

The final example writes a small Rust source file and its input with `files.install`, then uses a small stateless async operation to compile and execute it. The operation yields a `StringCommand`, so it participates in the normal preview/apply deploy and runs every time it is applied. The program locates `fd`, `rg` and `bat` under `$HOME/.cargo/bin` rather than relying on a login shell's PATH. That absolute-path choice is important for non-interactive SSH sessions, especially on RedHat.

The source does not need an external Rust library dependency. Instead, it uses `std::process::Command` to run the three command-line crates installed earlier: `fd-find` locates the input, `ripgrep` searches it and `bat` renders it. Each subprocess must succeed and return the expected text before the program prints its summary.

Save this as `run_program.py`:

```python
# run_program.py
import asyncio
import sys
from collections.abc import AsyncGenerator, Generator
from pathlib import Path

from reemote import (
    Command,
    Host,
    OpContext,
    OperationRequest,
    StringCommand,
    files,
    op,
)

_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", "PROGRAM", "compile_and_run", "deploy", "main"]

WORKDIR = "/tmp/reemote-rust-demo"
PROGRAM = r'''use std::env;
use std::path::PathBuf;
use std::process::Command;

fn run(binary: PathBuf, args: &[&str], dir: &str) -> String {
    let output = Command::new(binary)
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run installed crate");
    assert!(output.status.success(), "installed crate failed");
    String::from_utf8_lossy(&output.stdout).into_owned()
}

fn main() {
    let home = env::var("HOME").expect("HOME is not set");
    let bin = PathBuf::from(home).join(".cargo/bin");
    let dir = "/tmp/reemote-rust-demo";

    let found = run(bin.join("fd"), &["--type", "f", "notes.txt"], dir);
    assert!(found.contains("notes.txt"));

    let matches = run(
        bin.join("rg"),
        &["--no-heading", "Reemote", "notes.txt"],
        dir,
    );
    assert!(matches.contains("Reemote"));

    let rendered = run(
        bin.join("bat"),
        &["--style=plain", "--color=never", "notes.txt"],
        dir,
    );
    assert!(rendered.contains("Reemote"));

    println!("fd-find found {found}");
    println!("ripgrep matched {matches}");
    println!("bat rendered {rendered}");
}
'''


async def compile_and_run(
    ctx: OpContext, command: str, **kwargs
) -> AsyncGenerator[Command]:
    """Run the compile-and-execute command every time this operation is applied."""
    ctx.changed = True
    ctx.reason = "compile and run requested"
    yield StringCommand(command=command)


def deploy(host: Host) -> Generator[OperationRequest]:
    """Stage the source and input, then compile and execute them on the host."""
    yield op(
        files.install,
        name="Write Rust source",
        content=PROGRAM,
        dest=f"{WORKDIR}/main.rs",
        mode="0644",
    )
    yield op(
        files.install,
        name="Write program input",
        content="Reemote runs Rust with crates installed by Cargo.\n",
        dest=f"{WORKDIR}/notes.txt",
        mode="0644",
    )
    yield op(
        compile_and_run,
        name="Compile and run Rust program",
        command=f"rustc {WORKDIR}/main.rs -o {WORKDIR}/run-demo && {WORKDIR}/run-demo",
    )


async def main() -> None:
    await execute(deploy, apply_changes=parse_apply_flag(__doc__))


if __name__ == "__main__":
    asyncio.run(main())
```

Run the examples in order so the compiler and all three crate binaries already exist:

```bash
uv run python examples/articles/rust/install_rust.py --apply
uv run python examples/articles/rust/extend_rustup.py --apply
uv run python examples/articles/rust/install_crates.py --apply
uv run python examples/articles/rust/run_program.py --apply
```

The file writes are idempotent. The compile-and-run operation is intentionally stateless rather than fact-reconciled: it runs the program every time and fails if compilation or any invoked crate fails. A larger Rust service would normally build a release artifact in CI and deploy that artifact; this example keeps the whole toolchain visible on the host.

## Test the examples and check convergence

The pytest suite imports the actual files from `examples/articles/rust/`, checks their requests and runs the file and role examples against `SimulatedHost`. It also verifies that the canonical section is copied verbatim from the Alpine article and that every article script has a matching runnable file. No test opens an SSH connection or downloads a crate.

```bash
uv run pytest tests/test_rust_article_examples.py
```

Against the real inventory, preview each script before applying it. Run the provisioning scripts twice: their stateful requests should converge. The WebAssembly target should be added once, and the two Cargo crates should compile once. `run_program.py` remains an explicit execution step, so its stateless operation runs on every invocation by design.

## Implementation summary

Reemote expresses the whole workflow as Python state and ordinary operations. The `rustup` role provisions distribution packages, crosses a `FileExists` barrier and manages the Ubuntu toolchain plus Cargo crates. The `rustup` module adds typed facts and idempotent operations for toolchains, defaults, targets and components. The `cargo` module reconciles globally installed crates through Cargo's own installed-package listing.

The example program then uses those managed tools from a compiled Rust binary, while Reemote handles inventory selection, SSH transport, previews, elevation and structured results. The division is simple: rustup owns toolchains, Cargo owns crates and builds, and Reemote owns the repeatable server workflow around them.

## 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](https://discord.gg/de8MqzA3E)

