# Configuration management in Python, deploying a website

Setting up a website means keeping several machines in a known state: packages installed, configuration files written, services running, and certificates renewed. Reemote approaches that problem as a Python library: your inventory, deployment logic, and integrations are ordinary Python code, while Reemote supplies the facts, idempotent operations, and execution model that turn that code into changes on remote machines.

This article sets up a website in stages. It starts with nginx and a static landing page, adds a small Flask application behind a Unix socket, and finishes with optional HTTPS from Let's Encrypt. The same deploy pieces work against a disposable container or a real Ubuntu server; only the inventory changes. If you already know Python, loops, conditions, functions, imports, and pytest are available without translating the deployment into another configuration language. The managed machine needs a POSIX-compatible shell and an SSH or Docker connection, not Python or a Reemote agent.

Reemote is a younger project than the established configuration-management systems, so its built-in module collection and surrounding ecosystem are smaller. That is the trade-off for a compact, Python-native design. When an operation is missing, the answer is often a small Python function rather than a new plugin system.

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

## Inventory for real Ubuntu hosts

The canonical example proves the execution model without touching a server. The website examples now move to SSH and the repository's real Ubuntu inventory. Save an inventory like this as `inventory.json`:

```json
[
  {
    "host": "web1",
    "family": "Ubuntu",
    "connection": {
      "connector": "ssh",
      "address": "192.168.0.251",
      "username": "supervisor",
      "key_path": "~/.ssh/id_ed25519"
    },
    "group": "web",
    "tags": ["website"],
    "site_domain": "www.example.com",
    "certbot_email": "ops@example.com"
  }
]
```

Replace the address, user, key path, domain, and email with your own. `family` is required and selects Ubuntu's package and service tools. Unknown keys are preserved in `host.extra`, which is where `site_domain`, `certbot_email`, and an optional `"https": true` flag reach the deploy. For HTTPS on the Flask app, also set `"site_kind": "app"` (or a separate `app_domain`); without either selector, `https.py` manages the static site. Verify the host key and populate `~/.ssh/known_hosts` for production rather than disabling host-key checking.

The login user needs passwordless sudo for the website examples. They pass `sudo=True` on requests that write system paths; run-as users and passwords belong in the inventory's `privilege` mapping, not in individual operations. Ports 80 and 443 must be free, and a real HTTPS domain must resolve to the target before Certbot can complete its challenge.

## Runnable examples for the inventory Ubuntu host

The examples live in the Reemote Git repository: <https://github.com/kimjarvis/reemote/tree/main>. Clone it after configuring your SSH inventory:

```bash
git clone https://github.com/kimjarvis/reemote.git
cd reemote
uv sync
source .venv/bin/activate
```

Replace the cloned repository's `inventory.json` with your inventory, or edit its Ubuntu entry. Every script under [`examples/articles/website/`](https://github.com/kimjarvis/reemote/tree/main/examples/articles/website/) loads that file and selects only entries whose `family` is `Ubuntu`. Mutating scripts preview by default; add `--apply` only after reviewing the plan.

| Example | Article concept |
| --- | --- |
| [`hello.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/hello.py) | Canonical greeting adapted to real SSH hosts |
| [`operations.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/operations.py) | Typed facts plus file creation and removal |
| [`nginx.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/nginx.py) | nginx base and a change-driven reload |
| [`static_site.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/static_site.py) | Static content, an nginx server block, and convergence |
| [`web_app.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/web_app.py) | Flask, a virtualenv, service account, secret config, and systemd |
| [`https.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/https.py) | Certbot, HTTPS rendering, and the complete selected site |

Start with a read-only preview from the repository root:

```bash
uv run python examples/articles/website/hello.py
uv run python examples/articles/website/nginx.py --apply
```

`tests/test_website_article_examples.py` imports every script, exercises its deploy pieces against `SimulatedHost`, and checks the article's configuration fences. The regular suite opens no network connection. The scripts themselves are real-host programs: their previews gather live facts over SSH, and `--apply` makes the reviewed changes.

## Operations and facts

The greeting already used an operation. [`operations.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/operations.py) adds a direct fact read before creating or removing a file:

```python
hosts = [Host.from_inventory(entry) for entry in INVENTORY]
try:
    names = await gather_fact(hosts, server.LinuxName)
finally:
    await asyncio.gather(*(host.aclose() for host in hosts))
```

`gather_fact` returns a dictionary keyed by host name and leaves the supplied connections open, so the script closes them explicitly. A state operation then compares the file's current state with the request:

```python
yield op(files.file, name="Create hello file", path="/tmp/reemote-hello.txt", present=True)
```

Run `operations.py` to create the file, then run it with `--remove` to delete it. The operation yields a command only when the current state differs. A deploy is a generator driven once to prepare a plan and again to apply it; that is why operation arguments must be hashable and why branching on a live fact inside the generator is unsafe. Static inventory values such as `host.extra["site_domain"]` are identical in both phases and safe to use.

## nginx is the shared base

Both websites sit behind nginx. [`nginx.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/nginx.py) refreshes apt, installs nginx, disables the default site, and ensures the service is running and enabled:

```python
yield op(apt.update, name="Refresh apt indexes", sudo=True)
yield op(apt.packages, name="Install nginx", packages=("nginx",), sudo=True)
yield op(files.link, name="Disable default site",
         path="/etc/nginx/sites-enabled/default", present=False, sudo=True)
yield op(systemd.service, name="Run nginx", service="nginx",
         running=True, enabled=True, sudo=True)
```

The ordering is the dependency graph. Apply advances in lockstep, so the link operation reads the symlink after the package operation has installed nginx. On a second run, the package, link, and service-state requests report no change. `apt.update` is deliberately stateless and reports a change every time because it refreshes an index rather than converging a timestamped resource.

A configuration change still needs a reload. Reemote has no `notify` keyword; the example reads the completed report, freezes the changed host names, and runs a second deploy:

```python
changed_nginx = nginx_changed(report)
_, reload_report, _ = await run(
    INVENTORY, lambda host: reload_nginx(host, changed_nginx)
)
assert reload_report is not None
```

The frozen set makes the second deploy deterministic. An empty set produces no reload request. The same pattern handles the application restart later.

## Static content crosses as data

With nginx installed, [`static_site.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/static_site.py) adds a landing page and a server block. It composes the shared base with `yield from`, then renders the nginx text on the controller and passes the finished string to `files.install`.

There is no directory-sync operation and no remote interpretation of a controller path. To publish a folder, read its files on the controller and install each one's contents. The example keeps one self-contained HTML string:

```python
yield op(files.install, name="Install landing page",
         dest=f"/var/www/{domain}/index.html", content=INDEX_HTML,
         mode="0644", sudo=True)
```

The destination is derived from the validated `site_domain` inventory value, or the host name when no domain is configured. `files.install` creates parent directories, compares content, and writes through a temporary spool before installing the file with elevated permissions. Re-running the same deploy leaves an unchanged page alone.

The nginx configuration is equally ordinary Python. `render_site` replaces the domain and listener in a template; HTTPS adds the certificate paths. No template context becomes an operation argument, so the request remains a hashable string.

## The Flask application

The application stage adds more moving parts: a service account, a Python virtualenv, source and secret files, a systemd unit, and an nginx proxy. [`web_app.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/web_app.py) composes those pieces in dependency order.

nginx and gunicorn communicate through `/run/reemote-app/app.sock`. The deploy creates `reemote-app` and `reemote-socket` groups, gives the service account membership in the socket group, and adds `www-data` to that group. The unit's `RuntimeDirectory` creates the socket directory with mode `0770`, while `UMask=0007` keeps the socket group-accessible.

Reemote provides virtualenv and package operations, so no custom pip operation is needed:

```python
yield op(pip.venv, name="Create app virtualenv",
         path="/opt/reemote-app/venv", python="python3", sudo=True)
yield op(pip.packages, name="Install app dependencies",
         packages=("flask", "gunicorn"),
         pip="/opt/reemote-app/venv/bin/pip", sudo=True)
```

The application source, unit, and nginx proxy are installed as rendered text. The unit runs gunicorn from the virtualenv and reads its secret from `/etc/opt/reemote-app/config.py`, installed with mode `0640` and owned by the service account.

### Keep secrets out of the inventory

The Flask secret comes from the controller environment, not `inventory.json` and not a committed file:

```bash
export REEMOTE_APP_SECRET='use-a-secret-from-your-password-manager'
uv run python examples/articles/website/web_app.py
uv run python examples/articles/website/web_app.py --apply
```

`require_secret()` refuses to connect when the variable is absent. The deploy renders `SECRET_KEY='...'` into the protected configuration file. `files.install` reads the destination back with the same elevation when the login user cannot read a restrictive file, so content comparison and a second-run no-change still work. Use an encrypted secret store or your password manager to supply the environment value in automation.

After the main run, the example freezes hosts whose source, configuration, or unit changed and restarts only those applications. A converged run produces no restart request.

## HTTPS with Certbot

The final stage requests a real certificate. HTTPS is opt-in: add a resolvable `site_domain` and `certbot_email` to the inventory, or pass `--domain` explicitly. The host must also have `"https": true` in its inventory entry when no command-line domain is supplied. The inventory's `site_kind: "app"` or `app_domain` selects the Flask application; otherwise the static site is managed.

[`https.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/website/https.py) installs Certbot and uses a small custom operation. The operation reads whether the certificate file already exists and yields a command only when it does not:

```python
from reemote import StringCommand

cert_path = f"/etc/letsencrypt/live/{domain}/fullchain.pem"
if await ctx.facts.get(FileExists, cert_path):
    ctx.reason = f"certificate for {domain} already present"
    return
ctx.changed = True
ctx.reason = f"certificate for {domain} missing, will request"
command = (
    f"certbot certonly --webroot -w /var/www/{shlex.quote(domain)} "
    f"--non-interactive --agree-tos --email {shlex.quote(email)} "
    f"-d {shlex.quote(domain)}"
)
yield StringCommand(command)
```

The webroot challenge needs a directory that nginx can serve. Before requesting a missing certificate, the deploy creates `/var/www/<domain>`, writes a dedicated HTTP server block for `/.well-known/acme-challenge/`, and activates it. Activation repairs a missing, broken, or incorrect enabled symlink and reloads nginx whenever either the file or link changes. Certbot can then obtain the certificate. Only afterward does the deploy write and enable the port-443 HTTPS listener and certificate paths. The challenge site stays in place so future renewals continue to work; its reload is skipped only when the configuration and enabled symlink both match the requested state.

The deploy also installs an executable hook at `/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh`. Certbot runs deploy hooks after every successful renewal, so nginx loads renewed certificates without waiting for the next website deploy. The final configuration change triggers the normal changed-host reload.

```bash
uv run python examples/articles/website/https.py --domain www.example.com
uv run python examples/articles/website/https.py --domain www.example.com --apply
```

Use a domain that really points at your server. A reserved documentation domain or a private host name that public DNS cannot resolve cannot complete Let's Encrypt's HTTP-01 challenge. The preview still reads live facts and shows the planned work; it does not request a certificate or change the site.

## Test and check convergence

Run the focused offline checks with:

```bash
uv run pytest tests/test_website_article_examples.py tests/test_examples.py
```

The tests build and hash every request, run complete static and application deploys to convergence with `SimulatedHost`, verify preview/apply ordering and secret handling, and check that reloads and restarts target only changed hosts. They also exercise each script's main flow, compare article code fences with the runnable source, parse the inventory, and require every runnable example to appear in the index.

For a live check, preview first and apply only after reviewing the plan:

```bash
uv run python examples/articles/website/static_site.py
uv run python examples/articles/website/static_site.py --apply
uv run python examples/articles/website/static_site.py --apply
```

The first apply writes the page and nginx configuration. The second reports no change for those stateful requests and queues no reload. Package-index refreshes remain the expected stateless exception. Do not run the application or HTTPS examples against production merely to test the article; use a disposable VM with a test domain.

## What Reemote changes

The website deploy is ordinary Python: a shared generator for nginx, separate generators for the static and application sites, and small change-outcome barriers between complete runs. Inventory metadata chooses the site, while facts decide whether each operation has work to do.

There is no YAML inventory, second template language, remote agent, or callback-output parsing. Configuration is rendered control-side, secrets stay outside the inventory, and the plan, apply log, and typed facts remain inspectable data. nginx, Flask, systemd, and Certbot still have their own requirements; Reemote makes the sequence that connects them readable, reviewable, and reproducible.

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

