Using an Ansible role from a Python program is awkward: the role is YAML executed by Ansible's runner, so Python can only shell out to it or translate its behavior by hand. That makes roles difficult to compose, inspect and test like ordinary Python code, and it stands in the way of the larger goal of doing configuration management in Python. Reemote is a pure-Python configuration-management library whose inventory, facts, idempotent operations and staged deploys deliberately mirror Ansible's model, making it an ideal migration target without abandoning the semantics of the original role. That similarity supports a general methodology for migrating Ansible roles into reusable Python library code, which is what this article describes step by step.

This article walks through the migration of Jeff Geerling's Apache role, one small step at a time. Reemote already contains the finished migration in src/reemote/roles/apache.py, so the examples below lead toward code you can inspect and run rather than a hypothetical destination.

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.

Meet the Ansible role

The Alpine walkthrough demonstrates idempotence against an existing container separately. This article instead reuses persistent Ubuntu hosts, so its repeated runs demonstrate convergence against persistent host state rather than against a throwaway container.

The upstream role is geerlingguy/ansible-role-apache. Its default path installs Apache, refreshes package metadata where appropriate, probes the installed binary, selects version-specific variables, configures listening ports, enables modules and virtual hosts, starts the service and restarts it when notified configuration changes. It also supports SSL virtual hosts and separate Debian/Ubuntu and RedHat configuration layouts.

The migration starts with the Ubuntu path because its task graph is visible in a small number of files:

Upstream behavior Python destination
setup-Debian.yml: apt cache and packages apt.update, apt.packages
lineinfile on ports.conf pure transform plus files.transform
module and configuration symlinks files.link
template: vhosts.conf.j2 render to a string, then files.install
final service task systemd.service
notify: restart apache checkpoint, changed_hosts, service_handler
command: apache2 -v and register act(Shell, ...) barrier
defaults and OS-specific variables typed ApacheVars and resolved per-host values

The important point is that every Ansible construct has a destination before the role becomes reusable Python. A missing operation is a library gap to resolve, not an invitation to hide an imperative shell command inside the role.

Inventory for the migration hosts

The examples use the Ubuntu entries in the repository's inventory.json. An inventory remains ordinary data:

[ { "host": "ubuntu", "family": "Ubuntu", "connection": { "connector": "ssh", "address": "192.0.2.10", "port": 22, "username": "admin", "key_path": "~/.ssh/id_ed25519" } } ] 

Replace that documentation address, account and key with your own. The deployment account needs passwordless sudo for root-owned package, file and service state. family is required; it tells the Python code which package manager and service layout apply.

Use a disposable Ubuntu VM for the first run. These examples deliberately move Apache to port 8080 and remove the default virtual host in the final step. On a shared machine, first check what already owns ports 80, 443 and 8080.

Runnable examples for the Ubuntu inventory hosts

Clone the repository after configuring SSH, then edit its inventory.json Ubuntu entry:

git clone https://github.com/kimjarvis/reemote.git cd reemote uv sync --group docs uv pip install -e ".[templates]" 

The scripts live under examples/articles/migrate/. They load the Ubuntu entries from that inventory, preview by default and require --apply before changing a host. Run the steps in order.

Example Migration step
migrate_article_common.py Ubuntu inventory selection and preview/apply plumbing
migrate_install.py Package tasks become idempotent requests
migrate_probe.py A registered command result selects version-specific variables
migrate_page.py Explicit content replaces controller-side file lookup
migrate_configure.py Ports, vhost rendering, enablement and service state
migrate_modules.py Ansible loops become tuple-driven requests
migrate_handler.py Notifications become an in-stream checkpoint
migrate_role.py Run the finished typed library role

Preview any step with, for example:

uv run python examples/articles/migrate/migrate_install.py 

Add --apply only after reviewing that step's plan.

Shared inventory and safe execution

Each script imports the same small runner. Keeping it in one place makes the migration steps short without hiding what is executed: run(..., dry=True) plans request-only deploys, while run_waves(..., dry=True) previews the first wave of a deploy containing barriers.

# migrate_article_common.py import argparse import json import sys from collections.abc import Callable, Generator from pathlib import Path from reemote import ( ApplyReport, CommandError, Host, HostConnectionError, InventoryError, OperationRequest, PrivilegeError, format_log, format_plan, run, run_waves, validate_inventory, ) from reemote.stages import StageItem INVENTORY_PATH = Path(__file__).resolve().parents[3] / "inventory.json" Deploy = Callable[[Host], Generator[OperationRequest]] WaveDeploy = Callable[[Host], Generator[StageItem]] def _load_ubuntu_inventory() -> list[dict]: inventory = json.loads(INVENTORY_PATH.read_text(encoding="utf-8")) validate_inventory(inventory) ubuntu = [entry for entry in inventory if entry["family"] == "Ubuntu"] if not ubuntu: raise InventoryError(f"no Ubuntu hosts found in {INVENTORY_PATH}") return ubuntu def parse_apply_flag(description: str) -> bool: """Require an explicit opt-in before changing a real host.""" parser = argparse.ArgumentParser(description=description) parser.add_argument( "--apply", action="store_true", help="apply the previewed changes (default: preview only)", ) return parser.parse_args().apply async def execute(deploy: Deploy, *, apply_changes: bool) -> ApplyReport | None: """Preview a request-only deploy, then apply it only after opt-in.""" try: inventory = _load_ubuntu_inventory() print("== Ubuntu inventory ==") print(", ".join(entry["host"] for entry in inventory)) plans, report, _hosts = await run(inventory, deploy, dry=True) print("\n== Plan (read-only) ==") print(format_plan(plans)) assert report is None if not apply_changes: print("\nPreview only; pass --apply to change the host.") return None _plans, report, _hosts = await run(inventory, deploy) assert report is not None print("\n== Applied ==") print(format_log(report)) return report except (OSError, json.JSONDecodeError, InventoryError) as exc: print(f"\nERROR: {exc}", file=sys.stderr) raise SystemExit(1) from exc except (CommandError, HostConnectionError, PrivilegeError, ValueError) as exc: print(f"\nERROR: {exc}", file=sys.stderr) raise SystemExit(1) from exc async def execute_waves( deploy: WaveDeploy, *, apply_changes: bool ) -> ApplyReport | None: """Preview one wave of a barrier-bearing deploy, then apply after opt-in.""" return await _execute_waves(lambda _inventory: deploy, apply_changes=apply_changes) async def execute_waves_factory( deploy_factory: Callable[[list[dict]], WaveDeploy], *, apply_changes: bool, ) -> ApplyReport | None: """Build a barrier-bearing deploy inside the guarded runner.""" return await _execute_waves(deploy_factory, apply_changes=apply_changes) async def _execute_waves( deploy_factory: Callable[[list[dict]], WaveDeploy], *, apply_changes: bool, ) -> ApplyReport | None: try: inventory = _load_ubuntu_inventory() deploy = deploy_factory(inventory) print("== Ubuntu inventory ==") print(", ".join(entry["host"] for entry in inventory)) report, _hosts = await run_waves(inventory, deploy, dry=True) print("\n== One-wave preview (read-only) ==") print(report.tree()) if not apply_changes: print("\nPreview only; pass --apply to change the host.") return None report, _hosts = await run_waves(inventory, deploy) print("\n== Applied ==") print(report.tree()) return report except (OSError, json.JSONDecodeError, InventoryError) as exc: print(f"\nERROR: {exc}", file=sys.stderr) raise SystemExit(1) from exc except (CommandError, HostConnectionError, PrivilegeError, ValueError) as exc: print(f"\nERROR: {exc}", file=sys.stderr) raise SystemExit(1) from exc 

The runner is deliberately explicit about previews. Inventory loading, variable validation and deploy construction happen inside its guarded path, so inventory, transport, privilege and command failures become a one-line error rather than an import-time traceback or a pretend success. The final role uses execute_waves_factory so its factory receives the same validated inventory.

Step 1: translate package installation

Begin with the upstream setup tasks. update_cache=yes cache_valid_time=3600 becomes a separate cache-refresh request; the package list becomes an immutable tuple. Each request reads live facts and reports a real delta.

# migrate_install.py import asyncio import sys from collections.abc import Generator from pathlib import Path from reemote import Host, OperationRequest, apt, op _HERE = Path(__file__).resolve().parent if str(_HERE) not in sys.path: sys.path.insert(0, str(_HERE)) from migrate_article_common import execute, parse_apply_flag __all__ = ["deploy", "main"] def deploy(host: Host) -> Generator[OperationRequest]: """Refresh apt metadata within the role's one-hour cache window.""" yield op( apt.update, name="Update apt cache", cache_valid_time=3600, sudo=True, ) yield op( apt.packages, name="Install Apache", packages=("apache2", "apache2-utils"), sudo=True, ) async def main() -> None: await execute(deploy, apply_changes=parse_apply_flag(__doc__)) if __name__ == "__main__": asyncio.run(main()) 

This is already a complete migration of those two tasks. It is idempotent, runs across hosts in lockstep, and produces a plan before applying. sudo=True belongs on each request because Reemote has no play-level become.

Step 2: migrate a registered command result

The role probes apache2 -v, registers the output and uses it to select version-specific variables. Reemote expresses that read as an act barrier. The preceding package wave must finish before the probe runs, so the barrier also supplies the ordering that Ansible's task list supplied. The example parses the result and uses it to select a frozen version table.

# migrate_probe.py import asyncio import sys from collections.abc import Generator from pathlib import Path from reemote import Host, Shell, files, op from reemote.stages import StageItem, act _HERE = Path(__file__).resolve().parent if str(_HERE) not in sys.path: sys.path.insert(0, str(_HERE)) from migrate_article_common import execute_waves, parse_apply_flag from migrate_install import deploy as install __all__ = [ "PROBE", "VERSION_SETTINGS", "deploy", "main", "parse_version", "select_version_settings", ] PROBE = "/usr/sbin/apache2 -v" VERSION_SETTINGS = { "2.2": ("2.2", "000-default"), "2.4": ("2.4", "000-default.conf"), } def parse_version(stdout: str) -> str: """Parse the third banner field's slash-separated version.""" fields = stdout.split() if len(fields) < 3 or "/" not in fields[2]: raise ValueError(f"cannot parse Apache version from {stdout!r}") return fields[2].split("/")[1] def select_version_settings(version: str) -> tuple[str, str]: """Select the frozen vars table for the probed major.minor version.""" key = ".".join(version.split(".")[:2]) try: return VERSION_SETTINGS[key] except KeyError as exc: raise ValueError(f"unsupported Apache version: {version}") from exc def deploy(host: Host) -> Generator[StageItem]: yield from install(host) result = yield act(Source:https://dev.to/kimbofab/migrating-ansible-roles-to-python-290o

Related posts