# Migrating Ansible roles to Python

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`](https://github.com/kimjarvis/reemote/blob/main/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.

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

## 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`](https://github.com/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:

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

```bash
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/`](https://github.com/kimjarvis/reemote/tree/main/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`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_article_common.py) | Ubuntu inventory selection and preview/apply plumbing |
| [`migrate_install.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_install.py) | Package tasks become idempotent requests |
| [`migrate_probe.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_probe.py) | A registered command result selects version-specific variables |
| [`migrate_page.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_page.py) | Explicit content replaces controller-side file lookup |
| [`migrate_configure.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_configure.py) | Ports, vhost rendering, enablement and service state |
| [`migrate_modules.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_modules.py) | Ansible loops become tuple-driven requests |
| [`migrate_handler.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_handler.py) | Notifications become an in-stream checkpoint |
| [`migrate_role.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/migrate/migrate_role.py) | Run the finished typed library role |

Preview any step with, for example:

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

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

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

```python
# 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(Shell, command=PROBE, name="apache -v")
    if result["exit_status"] != 0:
        raise ValueError(
            f"{host.name}: Apache probe failed: {result['stderr'].strip()}"
        )
    version = parse_version(result["stdout"])
    vhosts_version, default_vhost_filename = select_version_settings(version)
    yield op(
        files.install,
        name="Record Apache version and vars",
        content=f"{version}\n{vhosts_version}\n{default_vhost_filename}\n",
        dest="/var/lib/apache2/migrated-version",
        mode="0644",
        sudo=True,
    )


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


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

An action barrier never raises merely because the command exited non-zero: its `Result` is data. The body therefore checks `exit_status` itself. Transport and privilege failures still raise. This distinction turns Ansible's `register` plus conditional handling into explicit Python control flow.

## Step 3: make file content explicit

Ansible's `copy` and `template` tasks resolve controller paths through role-directory conventions. Reemote's `files.install` instead takes the content itself. Start with a page that the virtual host will serve. This page is supporting example data, not a task from the upstream Apache role:

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

from reemote import Host, OperationRequest, files, 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__ = ["PAGE", "deploy", "main"]

DOCUMENT_ROOT = "/var/www/migrate-example"
PAGE = "<!doctype html>\n<title>Migrated Apache role</title>\n<h1>Hello from Python</h1>\n"


def deploy(host: Host) -> Generator[OperationRequest]:
    """Content is explicit Python data, not an implicit controller-side path."""
    yield op(
        files.directory,
        name="Create document root",
        path=DOCUMENT_ROOT,
        mode="0755",
        sudo=True,
    )
    yield op(
        files.install,
        name="Install index page",
        content=PAGE,
        dest=f"{DOCUMENT_ROOT}/index.html",
        mode="0644",
        sudo=True,
    )


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


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

The destination is on the remote host; the string is on the controller and is sent only when the remote content differs. There is no source-path lookup for a translator to reproduce.

## Step 4: translate ports, templates, links and service state

The role's `lineinfile` tasks become a pure text transform. Its Jinja template starts here as a small Python renderer. Both run before requests are built, so planning and applying receive identical content and callables.

```python
# migrate_configure.py
import asyncio
import re
import sys
from collections.abc import Callable, Generator
from pathlib import Path

from reemote import Host, OperationRequest, files, op, systemd

_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
from migrate_page import DOCUMENT_ROOT

__all__ = [
    "PORTS_CONF",
    "VHOSTS_CONF",
    "VHOST_NAME",
    "build_configure",
    "deploy",
    "listen_transform",
    "main",
    "render_vhost",
]

PORTS_CONF = "/etc/apache2/ports.conf"
VHOSTS_CONF = "/etc/apache2/sites-available/migrate-example.conf"
VHOST_NAME = "migrate.example.test"


def listen_transform(current: str | None) -> str:
    """Replace the last active Listen line, or append one when absent."""
    text = current if current is not None else ""
    lines = text.splitlines()
    replacement = "Listen 8080"
    last = None
    for index, line in enumerate(lines):
        if re.match(r"^Listen\s+", line):
            last = index
    if last is not None:
        lines[last] = replacement
    else:
        lines.append(replacement)
    return "\n".join(lines) + "\n"


def render_vhost(name: str, document_root: str) -> str:
    """A small pure renderer: the same inputs always produce the same text."""
    return (
        f"<VirtualHost *:8080>\n"
        f"  ServerName {name}\n"
        f"  DocumentRoot \"{document_root}\"\n"
        f"  <Directory \"{document_root}\">\n"
        f"    AllowOverride All\n"
        f"    Options -Indexes +FollowSymLinks\n"
        f"    Require all granted\n"
        f"  </Directory>\n"
        f"</VirtualHost>\n"
    )


def build_configure(
    mods: tuple[str, ...] = (),
) -> Callable[[Host], Generator[OperationRequest]]:
    """Close over immutable settings so planning and applying agree."""
    content = render_vhost(VHOST_NAME, DOCUMENT_ROOT)

    def deploy(host: Host) -> Generator[OperationRequest]:
        yield op(
            files.transform,
            name="Set Apache listen port",
            path=PORTS_CONF,
            transform=listen_transform,
            mode="0644",
            sudo=True,
        )
        yield op(
            files.file,
            name="Set ports.conf mode",
            path=PORTS_CONF,
            mode="0644",
            sudo=True,
        )
        for mod in mods:
            yield op(
                files.link,
                name=f"Enable Apache mod {mod}",
                path=f"/etc/apache2/mods-enabled/{mod}.load",
                target=f"/etc/apache2/mods-available/{mod}.load",
                sudo=True,
            )
        yield op(
            files.install,
            name="Install Apache vhost",
            content=content,
            dest=VHOSTS_CONF,
            mode="0644",
            user="root",
            group="root",
            sudo=True,
        )
        yield op(
            files.link,
            name="Enable Apache vhost",
            path="/etc/apache2/sites-enabled/migrate-example.conf",
            target=VHOSTS_CONF,
            sudo=True,
        )
        yield op(
            systemd.service,
            name="Start and enable Apache",
            service="apache2",
            running=True,
            enabled=True,
            sudo=True,
        )

    return deploy


def deploy(host: Host) -> Generator[OperationRequest]:
    yield from build_configure()(host)


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


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

The paired `files.file` request matters: `files.transform` converges content, while the separate file operation converges the mode even if only permissions drifted. The service task has no `notify` in the upstream role, so it starts Apache after configuration but does not itself queue the restart handler.

## Step 5: turn Ansible loops into Python loops

`with_items` over `apache_mods_enabled` becomes an ordinary loop over a tuple. The loop emits one named request per module, preserving both ordering and the notification channel.

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

from reemote import Host, OperationRequest

_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
from migrate_configure import build_configure

__all__ = ["MODS", "deploy", "main"]

MODS = ("rewrite", "ssl")


def deploy(host: Host) -> Generator[OperationRequest]:
    """The same configure stream now enables two modules from a tuple."""
    yield from build_configure(mods=MODS)(host)


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


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

A list would carry the same values but would violate Reemote's request hashability rule. Tuples make the configuration immutable and allow the runner to compare the requests produced by planning and applying.

## Step 6: migrate notify and the restart handler

A handler is a read of what changed. In a role, that read belongs inside the same per-host stream: a `checkpoint` immediately after configuration closes the wave and returns its `ApplyReport`. `changed_hosts` selects the notification names, and `service_handler` emits a restart only for those hosts.

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

from reemote import Host, changed_hosts
from reemote.handlers import service_handler
from reemote.stages import StageItem, checkpoint

_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_modules import MODS
from migrate_modules import deploy as configure

__all__ = ["NOTIFYING", "deploy", "main"]

NOTIFYING = (
    "Set Apache listen port",
    "Set ports.conf mode",
    "Install Apache vhost",
    "Enable Apache vhost",
    *(f"Enable Apache mod {mod}" for mod in MODS),
)


def deploy(host: Host) -> Generator[StageItem]:
    """Configure, close that wave, and restart only hosts that changed."""
    yield from configure(host)
    report = yield checkpoint("configure done")
    notified = changed_hosts(report, NOTIFYING)
    yield from service_handler(notified, ("apache2",), action="restarted")(host)


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


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

The checkpoint's position is load-bearing. It must immediately follow the requests it reports on. Put another barrier between configuration and the checkpoint and that barrier closes the configuration wave; the later checkpoint sees only the barrier-only wave and silently notifies nobody. A converged rerun runs the checkpoint but emits no handler request.

## Step 7: use the completed library role

The earlier steps teach the mappings. The finished role adds typed variables, multiple virtual hosts, SSL certificate reads, optional default-vhost removal and the RedHat branch. It is already part of Reemote; import it rather than maintaining a private copy.

```python
# migrate_role.py
import asyncio
import sys
from pathlib import Path

from reemote import resolve_vars
from reemote.roles import ApacheVars, apache

_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_factory, parse_apply_flag

__all__ = ["build_deploy", "main"]

OVERRIDES = {
    "listen_port": 8080,
    "remove_default_vhost": True,
    "vhosts": (
        {
            "servername": "migrate.example.test",
            "documentroot": "/var/www/migrate-example",
        },
    ),
}


def build_deploy(inventory: list[dict]):
    """Validate inventory values before any host is contacted."""
    vars_set = resolve_vars(ApacheVars, "apache", inventory, overrides=OVERRIDES)
    return apache(vars_set)


async def main() -> None:
    await execute_waves_factory(
        build_deploy, apply_changes=parse_apply_flag(__doc__)
    )


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

`ApacheVars` is a frozen pydantic model. `resolve_vars` applies model defaults, then the inventory's `roles.apache` mapping, then call-site overrides. Unknown keys and invalid values fail before a host is contacted. Sequences become tuples, so the resolved configuration is hashable.

On Ubuntu, the role's stream is installation, the version-probe barrier, configuration and then the checkpoint-driven handler. Each configured SSL virtual host adds a certificate-existence barrier before configuration. On RedHat, it selects `httpd`, writes module stubs into `conf.modules.d`, places the vhosts file in `conf.d`, and performs the RHEL 8+ localhost-certificate checks. The [Apache role reference](../roles/apache.md) documents the complete coverage and deliberate deviations.

## Test every intermediate step

A migration is not complete when its happy path runs once. Each example has offline pytest coverage that builds its real requests and drives stateful examples through Reemote's execution engine against `SimulatedHost`. No test contacts the inventory hosts.

```bash
uv run pytest tests/test_migrate_article_examples.py -q
```

The tests check request names, operation selection, elevation, immutable arguments, rendered content, transform fixpoints, handler gating, probe parsing and convergence. The final role is also exercised twice against the same persistent simulated hosts: the first pass changes state and queues a restart; the second changes nothing and has no handler wave.

Against your own disposable Ubuntu host, apply the steps in order. The module step is intentionally preview-only: Step 6 applies the same configuration stream and needs a real module change to demonstrate the restart handler.

```bash
uv run python examples/articles/migrate/migrate_install.py --apply
uv run python examples/articles/migrate/migrate_probe.py --apply
uv run python examples/articles/migrate/migrate_page.py --apply
uv run python examples/articles/migrate/migrate_configure.py --apply
uv run python examples/articles/migrate/migrate_modules.py
uv run python examples/articles/migrate/migrate_handler.py --apply
uv run python examples/articles/migrate/migrate_role.py --apply
uv run python examples/articles/migrate/migrate_role.py --apply
```

The first handler run should restart Apache because the module links changed. The last command should report no configuration changes and no restart. A version probe still runs on every pass because it is a read, not a cached plan value. That is expected and demonstrates that convergence comes from facts rather than skipped execution.

## How Reemote enables the migration

The Apache conversion is useful evidence for a larger argument about AI-assisted migration. Ask a model to rewrite an Ansible role in unspecified Python and it usually reaches for the nearest primitives: `subprocess`, shell strings and hand-written file writes. The program may reproduce the happy path, but it invents a new configuration engine along the way. It must rediscover idempotence, fleet ordering, previews and change identification, and different attempts produce different arrangements.

The missing ingredient is a target idiom. Ansible roles inherit their operational guarantees from Ansible. A Python translation preserves those guarantees only if there is a Python configuration-management library with the same conceptual shape: inventory, facts, idempotent operations, handlers and structured results. Reemote supplies that shape.

That changes the work from architecture design to mapping. The Apache task graph becomes a sequence of recognizable decisions: package tasks become package operations, `lineinfile` becomes a pure transform, a template becomes rendered content, a notification becomes a checkpoint, and a command result becomes an action barrier. The translator does not need to invent SSH concurrency or parse callback output. It works inside an existing, documented vocabulary.

The same properties make the result reviewable. Requests are data, content is explicit, and a dry run returns a plan that a program can inspect. Tests can assert on generated requests without a server and then run the real driver against simulated hosts. A human reviews a bounded diff against the upstream task list rather than auditing a new automation framework.

This is also why the migration can be performed by AI. A model can read the role, enumerate its tasks and variables, map each construct to Reemote, generate the Python and write the tests. Reemote is not an automatic transpiler: the model performs the translation and a human reviews it. But the destination library makes that translation convergent. Each successful role becomes another example of the pattern, improving the next migration rather than leaving every model to improvise from shell commands.

The library still has boundaries. It is Linux-only, it does not translate package names between operating systems, and it does not provide a Galaxy-equivalent catalogue of every third-party role. Choosing the right family branch remains engineering work. Those boundaries are preferable to hidden ones: the migration stays explicit about what is supported, what is scoped out and which deviations were deliberate.

## Implementation summary

The upstream Apache role's knowledge survives in [`reemote.roles.apache`](https://github.com/kimjarvis/reemote/blob/main/src/reemote/roles/apache.py) as a library deploy:

- **Package setup** becomes `apt.update(cache_valid_time=3600)` and `apt.packages` on Ubuntu, or `dnf.packages` on RedHat.
- **Version dispatch** becomes an installed-binary probe barrier followed by the appropriate frozen variable table.
- **Port editing** becomes pure `lineinfile` transforms applied with `files.transform`, paired with mode convergence.
- **Module and configuration enablement** becomes typed symlinks on Ubuntu and `LoadModule` file stubs on RedHat.
- **Virtual-host templates** become controller-side rendered strings installed into the family's configuration layout.
- **SSL checks** become per-certificate existence barriers, with the RedHat localhost-certificate path preserved.
- **Service state** becomes `systemd.service`, keeping running and enabled state explicit.
- **Notifications and handlers** become a checkpoint, a changed-host set and a conditional restart.

The result is reusable by other Python programs: resolve `ApacheVars`, call `apache(...)`, compose the resulting deploy and inspect its structured report. The configuration knowledge from Ansible remains; the orchestration is now ordinary Python that can be imported, tested and awaited.

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

