# Configure log rotation with Python

Logrotate is the mechanism that stops application logs from filling the disk: on a schedule it renames the current log file, compresses the older ones, deletes everything beyond the retention count, and can signal the application to reopen its files. Its policy lives in `/etc/logrotate.conf` plus one small drop-in file per application under `/etc/logrotate.d`, and it runs from a cron job or — on Ubuntu — a systemd timer. Reemote is a pure-Python configuration-management library that manages that policy as ordinary Python: it reads the installed version, the parsed rules and the last-rotation state from the target, renders each drop-in on the control side from typed arguments, and previews every change before applying it. This article starts with the canonical Reemote quickstart, then builds persistent, real-host examples for installing logrotate, deploying typed and whole-file drop-ins, keeping the timer convergent, inspecting rotation state, forcing a rotation and cleaning up.

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

Unlike the throwaway-container quickstart, the migration examples below reuse the same Ubuntu hosts, so repeated runs demonstrate convergence against persistent host state.

## How logrotate works

A logrotate configuration file contains one or more stanzas. The header lists the log path patterns the stanza manages; the braced block holds the directives:

```text
/var/log/myapp/*.log {
    daily
    rotate 14
    compress
    create 0640 root adm
}
```

The directives fall into a few groups, and each group has a direct Reemote expression described below:

- **Frequency** — `hourly`, `daily`, `weekly`, `monthly` or `yearly`. Logrotate rotates a file when its entry in the state file is older than the interval; it writes the new timestamp afterwards. That state file is `/var/lib/logrotate/status`, and it is why a job that runs every day only rotates a `daily` log once per day.
- **Retention and compression** — `rotate N` keeps N old copies, `compress` gzips rotated logs and `delaycompress` leaves the newest rotated file plain for one more cycle so it stays easy to grep.
- **File handling** — `create mode owner group` writes a fresh log with those attributes after rotation; `copytruncate` instead copies and empties the file in place for applications that cannot be told to reopen it. `missingok` and `notifempty` skip absent and empty logs rather than failing the run. Size triggers such as `maxsize` rotate between scheduled runs once a file grows past the limit.
- **Scripts** — `prerotate` and `postrotate` blocks, each terminated by `endscript`, run shell commands around the rotation; `sharedscripts` runs them once for the whole stanza instead of once per matched file.
- **The trigger itself** — Ubuntu ships a `logrotate.timer` systemd unit; other systems call logrotate from cron. Either way, logrotate itself is a plain command, so the same configuration is verifiable by hand at any time.

For the wider picture — the create-versus-copytruncate trade-off, size-based policies and disk-capacity thinking — the [Better Stack logrotate guide](https://betterstack.com/community/guides/logging/how-to-manage-log-files-with-logrotate-on-ubuntu-20-04/), the [Dash0 log-rotation guide](https://www.dash0.com/guides/log-rotation-linux-logrotate), [Datadog's log-file control post](https://www.datadoghq.com/blog/log-file-control-with-logrotate/) and [Red Hat's setting-logrotate note](https://www.redhat.com/en/blog/setting-logrotate) are worth reading before writing production policies.

## The Reemote logrotate module

The [logrotate module](../modules/logrotate.md) is deliberately small and honest about its edges. Its facts inspect the installed release, parse the rules from `/etc/logrotate.conf` and every regular file directly under `/etc/logrotate.d` in one round trip, and read the per-log timestamps from the status file. Its operations manage one validated drop-in from typed arguments, run `logrotate -d` against a configuration file, force an immediate rotation and converge the running and boot-enabled state of `logrotate.timer`.

The managed-drop-in operation is a spool-and-install write: it renders the complete file text from the typed arguments, compares that text against the current file, uploads changed content to a private `/tmp` spool directory created as login-user-owned mode `0700`, validates those exact bytes with `logrotate -d`, and only then installs the file as `root:root` mode `0644`. A validation failure stops before the live configuration changes, and `present=False` removes the file. Because the comparison is textual, an unchanged rule produces no transfer and no write.

Three boundaries matter when composing it. The module does not install distribution packages — pair it with the [apt](../modules/apt.md), `dnf` or `apk` module first. It is systemd-only for scheduling — Alpine and cron-based hosts should manage their job through the [crontab](../modules/crontab.md) or [openrc](../modules/openrc.md) modules instead. And its typed arguments cover the common directives, not the whole logrotate grammar: options such as `maxsize`, `copytruncate` or `dateext` have no typed parameter, and the right way to manage a stanza that needs them is to own that one drop-in file wholesale with `files.install` and follow it with the module's `validate` operation. Both shapes appear below.

## What managing logrotate takes

A rotation policy needs a small set of distinct jobs, and each one is a plain Reemote expression — no template files, because the drop-in text is rendered on the control side from typed arguments:

- Ensuring the `logrotate` binary exists: `op(apt.packages, packages=("logrotate",), sudo=True)`.
- Managing one `/etc/logrotate.d` drop-in: `op(logrotate.rule, paths=(...), config_file=..., ...)`.
- Managing a fleet of policies: an ordinary Python loop yielding one `logrotate.rule` request per row.
- Validating candidate bytes with `logrotate -d`: built into `logrotate.rule` (`validate=True`), or `op(logrotate.validate, ...)`.
- Directives with no typed parameter: whole-file ownership with `files.install`.
- Forcing a rotation now: `op(logrotate.rotate, config_file=...)`.
- Reading rotation state: the `LogrotateStatus` fact.
- Managing the trigger: `op(logrotate.service, ...)` on systemd hosts.
- Removing a managed drop-in: `present=False` on the same rule request.

Sequence-valued arguments are tuples (`paths=(...)`, `create=("0640", "root", "adm")`) because every operation request must remain hashable between the preview and the apply. The privilege flags come from the request (`sudo=True`), and the run-as user is a property of the inventory, never of the operation.

## Inventory for the logrotate host

The examples use the repository's real Ubuntu SSH host. Save an equivalent inventory as `inventory.json`:

```json
[
  {
    "host": "ubuntu",
    "family": "Ubuntu",
    "connection": {
      "connector": "ssh",
      "address": "192.168.0.251",
      "port": 22,
      "username": "supervisor",
      "key_path": "~/.ssh/id_ed25519"
    },
    "group": "ubuntu",
    "tags": ["ubuntu_host", "apt_package_manager"]
  }
]
```

Replace the address, user and key path with your own. Every mutating request writes under `/etc/logrotate.d`, `/var/log/reemote-logrotate-article` or `/usr/local/sbin`, so the `supervisor` login needs passwordless sudo. Verify the host key and populate `~/.ssh/known_hosts` rather than disabling host-key checking; see the [SSH connector reference](../connectors/ssh.md) for the connection options.

## Runnable examples for the inventory Ubuntu host

Clone the repository and edit its `inventory.json`, or replace that file with the inventory above:

```bash
git clone https://github.com/kimjarvis/reemote.git
cd reemote
```

The scripts under [`examples/articles/logrotate/`](https://github.com/kimjarvis/reemote/tree/main/examples/articles/logrotate/) load that inventory, select only entries whose `family` is `Ubuntu`, and use `sudo` for the root-owned state. Mutating scripts preview by default and require `--apply`; the inspection script is read-only.

| Example | Article concept |
| --- | --- |
| [`stage_logs.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/stage_logs.py) | Stage the fixture logs and the reload script the rules signal |
| [`install_package.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/install_package.py) | `apt.packages` ensures the logrotate binary exists |
| [`app_rule.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/app_rule.py) | Manage one drop-in from typed arguments |
| [`multi_app.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/multi_app.py) | An ordinary Python loop over a rule table |
| [`size_based.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/size_based.py) | Own a drop-in with untyped directives wholesale, then validate it |
| [`timer_state.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/timer_state.py) | Converge `logrotate.timer` running and enabled |
| [`inspect_logrotate.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/inspect_logrotate.py) | Gather version, parsed-rule and rotation-state facts |
| [`rotate_now.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/rotate_now.py) | Force an immediate, deliberately non-idempotent rotation |
| [`remove_rules.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/logrotate/remove_rules.py) | Remove every managed drop-in and fixture |

Run a read-only preview from the repository root:

```bash
uv run python examples/articles/logrotate/app_rule.py
```

## Stage the fixtures first

The rules below manage logs for a synthetic application rather than for whatever happens to run on the host. This example creates the root-owned log directory `/var/log/reemote-logrotate-article`, installs five small fixture logs owned `root:adm` mode `0640`, and writes the reload script `/usr/local/sbin/reemote-logrotate-article-reload.sh` that the `postrotate` blocks will signal. The reload script appends one line to `postrotate.log` inside the same directory, which later gives the inspection example visible proof that a rotation ran:

```python
# stage_logs.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Stage the fixture logs and reload script used by the logrotate article rules."""

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 logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = [
    "API_LOG",
    "APP_LOG",
    "INVENTORY",
    "LARGE_LOG",
    "LOG_DIR",
    "LOG_FILES",
    "PROXY_LOG",
    "RELOAD_LOG",
    "RELOAD_SCRIPT",
    "RELOAD_SCRIPT_TEXT",
    "WORKER_LOG",
    "deploy",
    "main",
]

LOG_DIR = "/var/log/reemote-logrotate-article"
APP_LOG = f"{LOG_DIR}/app.log"
API_LOG = f"{LOG_DIR}/api.log"
WORKER_LOG = f"{LOG_DIR}/worker.log"
PROXY_LOG = f"{LOG_DIR}/proxy.log"
LARGE_LOG = f"{LOG_DIR}/large.log"
RELOAD_SCRIPT = "/usr/local/sbin/reemote-logrotate-article-reload.sh"
RELOAD_LOG = f"{LOG_DIR}/postrotate.log"
RELOAD_SCRIPT_TEXT = (
    "#!/bin/sh\n"
    f"printf 'reloaded %s %s\\n' \"$(date -u +%FT%TZ)\" \"$(hostname)\" "
    f">> {RELOAD_LOG}\n"
)


def _fixture(name: str, lines: int) -> str:
    return "".join(
        f"[2026-12-01 {index % 24:02d}:00:00] {name} INFO scheduled entry {index}\n"
        for index in range(lines)
    )


LOG_FILES = {
    APP_LOG: _fixture("app", 6),
    API_LOG: _fixture("api", 6),
    WORKER_LOG: _fixture("worker", 6),
    PROXY_LOG: _fixture("proxy", 6),
    LARGE_LOG: _fixture("large", 24),
}


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        files.directory,
        name="Create fixture log directory",
        path=LOG_DIR,
        user="root",
        group="adm",
        mode="0755",
        sudo=True,
        when=is_ubuntu,
    )
    for path, content in LOG_FILES.items():
        yield op(
            files.install,
            name=f"Stage {path.rsplit('/', 1)[-1]}",
            content=content,
            dest=path,
            user="root",
            group="adm",
            mode="0640",
            sudo=True,
            when=is_ubuntu,
        )
    yield op(
        files.install,
        name="Install reload script",
        content=RELOAD_SCRIPT_TEXT,
        dest=RELOAD_SCRIPT,
        user="root",
        group="root",
        mode="0755",
        sudo=True,
        when=is_ubuntu,
    )


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


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

Run `python examples/articles/logrotate/stage_logs.py`, review the plan, then repeat with `--apply`. Re-applying overwrites the fixture content with the same text, which is exactly the convergence behaviour the later sections rely on.

## Ensure the package is installed

Ubuntu ships logrotate, but a configuration deploy should not assume it: the module deliberately leaves installation to the package modules. One `apt.packages` request guarantees the binary that every later fact read and every `logrotate -d` validation depends on:

```python
# install_package.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Ensure the logrotate package is installed on the inventory Ubuntu hosts."""

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 logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["INVENTORY", "PACKAGES", "deploy", "main"]

PACKAGES = ("logrotate",)


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        apt.packages,
        name="Install logrotate",
        packages=PACKAGES,
        sudo=True,
        when=is_ubuntu,
    )


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


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

The second apply reports no change once the package is present, because the fact read shows it installed already.

## Manage one drop-in from typed arguments

The canonical case — an application log rotated daily, kept for two weeks, compressed after one plain cycle, recreated with explicit ownership, with a reload signal afterwards — is one `logrotate.rule` request. No template file exists anywhere; the request's typed arguments are the configuration:

```python
# app_rule.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Manage the article's single application logrotate drop-in from typed arguments."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, logrotate, op

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from stage_logs import APP_LOG, RELOAD_SCRIPT

__all__ = ["APP_DROPIN", "INVENTORY", "deploy", "main"]

APP_DROPIN = "/etc/logrotate.d/reemote-logrotate-article-app"


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        logrotate.rule,
        name="Rotate the app log daily",
        paths=(APP_LOG,),
        config_file=APP_DROPIN,
        frequency="daily",
        rotate=14,
        compress=True,
        delaycompress=True,
        missingok=True,
        notifempty=True,
        create=("0640", "root", "adm"),
        sharedscripts=True,
        postrotate=RELOAD_SCRIPT,
        sudo=True,
        when=is_ubuntu,
    )


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


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

With the arguments above, the rendered drop-in `/etc/logrotate.d/reemote-logrotate-article-app` is exactly this file:

```text
/var/log/reemote-logrotate-article/app.log {
    daily
    rotate 14
    compress
    delaycompress
    missingok
    notifempty
    create 0640 root adm
    sharedscripts
    postrotate
        /usr/local/sbin/reemote-logrotate-article-reload.sh
    endscript
}
```

The operation compares that whole text against the current file before doing anything, so the first apply spools, validates and installs, and every later apply reports “already matches the desired rule” without sending a write. Validation runs on the spooled bytes, so a rejected rule never reaches `/etc/logrotate.d`.

## Deploy a set of per-application rules

A fleet of rotation policies is a table of plain Python rows, and the loop yields one typed request per row — each request independently compares, spools, validates and installs its own drop-in:

```python
# multi_app.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Deploy three per-application logrotate drop-ins from one typed rule table."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, logrotate, op

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from stage_logs import API_LOG, PROXY_LOG, RELOAD_SCRIPT, WORKER_LOG

__all__ = ["DROPIN_DIR", "INVENTORY", "RULES", "deploy", "main"]

DROPIN_DIR = "/etc/logrotate.d"

# config file, log path, frequency, retention count and create mode per entry.
RULES = (
    ("reemote-logrotate-article-api", API_LOG, "daily", 14, "0640"),
    ("reemote-logrotate-article-worker", WORKER_LOG, "weekly", 8, "0640"),
    ("reemote-logrotate-article-proxy", PROXY_LOG, "daily", 7, "0600"),
)


def deploy(host: Host) -> Generator[OperationRequest]:
    for basename, path, frequency, rotate, mode in RULES:
        yield op(
            logrotate.rule,
            name=f"Rotate {basename.rsplit('-', 1)[-1]} {frequency}",
            paths=(path,),
            config_file=f"{DROPIN_DIR}/{basename}",
            frequency=frequency,
            rotate=rotate,
            compress=True,
            delaycompress=True,
            missingok=True,
            notifempty=True,
            create=(mode, "root", "adm"),
            sharedscripts=True,
            postrotate=RELOAD_SCRIPT,
            sudo=True,
            when=is_ubuntu,
        )


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


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

The three stanzas cover different logs at different intervals — `api.log` daily with fourteen copies, `worker.log` weekly with eight, `proxy.log` daily with seven and a tighter `0600` recreate. The path sets are disjoint on purpose: logrotate rejects two stanzas that manage the same file, and one request per drop-in file keeps each policy owned by exactly one row.

## Own a size-based drop-in wholesale

Size-driven rotation depends on directives the typed rule does not model: `maxsize` only makes sense alongside a frequency trigger, `copytruncate` replaces the whole create-and-signal dance for applications that cannot reopen their logs, and `dateext` changes how rotated files are named. For a stanza like this, own the complete drop-in with `files.install` and run `logrotate.validate` over it afterwards:

```python
# size_based.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Own one size-based drop-in wholesale, then validate it with logrotate -d."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

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

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from stage_logs import LARGE_LOG

__all__ = ["INVENTORY", "LARGE_DROPIN", "LARGE_DROPIN_CONTENT", "deploy", "main"]

LARGE_DROPIN = "/etc/logrotate.d/reemote-logrotate-article-large"
LARGE_DROPIN_CONTENT = f"""# Managed by Reemote; this file is exclusively owned by size_based.py.
{LARGE_LOG} {{
    weekly
    maxsize 5M
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
    dateext
    dateformat -%Y%m%d
}}
"""


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        files.install,
        name="Install size-based drop-in",
        content=LARGE_DROPIN_CONTENT,
        dest=LARGE_DROPIN,
        user="root",
        group="root",
        mode="0644",
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        logrotate.validate,
        name="Validate size-based drop-in",
        config_file=LARGE_DROPIN,
        sudo=True,
        when=is_ubuntu,
    )


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


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

`files.install` compares content and converges on a second pass like any managed file. `logrotate.validate` is intentionally stateless: it always runs `logrotate -d` against the named configuration file, so this deploy re-validates the drop-in on every run even when the file is unchanged. That is the point — the validation result reflects the live host, not a cached assumption. A failing validation raises at apply time and stops the deploy before any later request runs.

## Keep the timer running

On Ubuntu the rotation schedule is driven by `logrotate.timer`. The `logrotate.service` operation converges both axes of that unit — active now and enabled at boot — using the same read-then-act discipline as the rest of the module:

```python
# timer_state.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Converge the logrotate systemd timer to running and boot-enabled state."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, logrotate, op

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

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


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        logrotate.service,
        name="Ensure logrotate timer runs at boot",
        running=True,
        enabled=True,
        sudo=True,
        when=is_ubuntu,
    )


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


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

On a stock Ubuntu host the timer is usually already active and enabled, so this request typically plans no change. Stop or mask the timer by hand and the same script starts and enables it again. The operation is systemd-only by design; on Alpine, schedule through `crontab` or the OpenRC anacron service instead.

## Inspect the result

Facts answer the three operational questions about logrotate without parsing human output: is the binary there and what release is it, which rules does the host actually have parsed, and when was each log last rotated? This read-only script answers all three across every Ubuntu host and prints structured data:

```python
# inspect_logrotate.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Read logrotate's version, parsed rules and last-rotation state from real hosts."""

import asyncio
import json
import shlex
import sys
from pathlib import Path

from reemote import (
    Host,
    LogrotateConfig,
    LogrotateStatus,
    LogrotateVersion,
    gather_fact,
)

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from logrotate_article_common import INVENTORY

__all__ = ["INVENTORY", "STATUS_SHELL", "main"]

# Ubuntu ships /var/lib/logrotate/status root-owned and mode 0640, so the
# unprivileged fact read comes back empty for a sudo login. The script runs
# the fact's own guarded command elevated and reuses the fact's parser.
STATUS_SHELL = f"sh -c {shlex.quote(LogrotateStatus.COMMAND)}"


async def main() -> None:
    hosts = [Host.from_inventory(entry) for entry in INVENTORY]
    try:
        versions = await gather_fact(hosts, LogrotateVersion)
        configs = await gather_fact(hosts, LogrotateConfig)
        statuses = {}
        for host in hosts:
            stdout = await host.run_shell_sudo(STATUS_SHELL)
            statuses[host.name] = LogrotateStatus.parse(stdout.splitlines())
    finally:
        await asyncio.gather(*(host.aclose() for host in hosts))
    for host in hosts:
        print(f"== {host.name}: logrotate version ==")
        print(versions[host.name])
        print(f"== {host.name}: parsed rules ==")
        print(json.dumps(configs[host.name], indent=2))
        print(f"== {host.name}: last-rotation status ==")
        print(json.dumps(statuses[host.name], indent=2))


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

`LogrotateVersion` returns the release string or `None` when the binary is absent, and `LogrotateConfig` returns one record per parsed stanza with its source file, path patterns, frequency, retention and scripts — both are ordinary unprivileged `gather_fact` reads. The last-rotation state needs one concession: Ubuntu keeps `/var/lib/logrotate/status` root-owned mode `0640`, so the script runs the `LogrotateStatus` fact's own guarded command through `host.run_shell_sudo` and feeds the output to the fact's `parse` classmethod, reusing the parser instead of duplicating it. Like `gather_action` but unlike `run`, `gather_fact` does not own the hosts, hence the explicit `aclose()` in the `finally` block. Run it with `python examples/articles/logrotate/inspect_logrotate.py` after applying the rules above, and the parsed-rules section should include the drop-ins this article created.

## Force a rotation

The status file is what normally holds a rotation back until its interval elapses. `logrotate.rotate` bypasses that gate with `logrotate -vf` — optionally against an explicit state file — which makes it the manual verification step of the troubleshooting workflow and the one operation in the module that is intentionally non-idempotent:

```python
# rotate_now.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Force one immediate rotation of the article's app drop-in with logrotate -vf.

This operation is intentionally non-idempotent: every applied pass rotates the
matching log files again, regardless of the schedule or the status file. Run it
only where an immediate rotation is intended, as a manual verification step
after the rules have converged.
"""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

from reemote import Host, OperationRequest, logrotate, op

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from app_rule import APP_DROPIN
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag

__all__ = ["APP_DROPIN", "INVENTORY", "deploy", "main"]


def deploy(host: Host) -> Generator[OperationRequest]:
    yield op(
        logrotate.rotate,
        name="Force rotation of the app log",
        config_file=APP_DROPIN,
        sudo=True,
        when=is_ubuntu,
    )


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


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

After applying it, the fixture directory holds a rotated, still-uncompressed `app.log.1` (the `delaycompress` directive spares it one cycle), `app.log` has been recreated `0640 root:adm`, the status file shows a fresh timestamp, and `postrotate.log` contains the reload script's line. Repeating the command rotates again on purpose; keep it out of any zero-change convergence run.

## Remove the managed drop-ins

`present=False` removes a managed drop-in and reports no change when it is already absent. This example removes all five article drop-ins, then the fixture directory and the reload script, leaving the host exactly as it was before the article:

```python
# remove_rules.py
# Copyright (c) 2026 Kim Jarvis.
# SPDX-License-Identifier: EPL-2.0

"""Remove every drop-in, fixture log and script the article creates."""

import asyncio
import sys
from collections.abc import Generator
from pathlib import Path

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

_HERE = Path(__file__).resolve().parent
if str(_HERE) not in sys.path:
    sys.path.insert(0, str(_HERE))
from app_rule import APP_DROPIN
from logrotate_article_common import INVENTORY, execute, is_ubuntu, parse_apply_flag
from multi_app import DROPIN_DIR, RULES
from size_based import LARGE_DROPIN
from stage_logs import LOG_DIR, RELOAD_SCRIPT

__all__ = ["ALL_DROPINS", "INVENTORY", "deploy", "main"]

ALL_DROPINS = (
    APP_DROPIN,
    LARGE_DROPIN,
    *(f"{DROPIN_DIR}/{basename}" for basename, *_rest in RULES),
)


def deploy(host: Host) -> Generator[OperationRequest]:
    for config_file in ALL_DROPINS:
        yield op(
            logrotate.rule,
            name=f"Remove {config_file.rsplit('/', 1)[-1]}",
            paths=(),
            config_file=config_file,
            present=False,
            sudo=True,
            when=is_ubuntu,
        )
    yield op(
        files.directory,
        name="Remove fixture log directory",
        path=LOG_DIR,
        present=False,
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        files.file,
        name="Remove reload script",
        path=RELOAD_SCRIPT,
        present=False,
        sudo=True,
        when=is_ubuntu,
    )


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


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

The removal only ever targets the named files — it is not a sweep of `/etc/logrotate.d`, and unmanaged files in that directory are never touched.

## Test the examples, then check convergence

The focused pytest suite imports every script, validates its inventory and requests, runs each deploy twice on a persistent simulated host, replays the documented sequences and checks that the article's Python fences match the runnable files:

```bash
.venv/bin/python -m pytest -q tests/test_logrotate_article_examples.py
```

For the real Ubuntu host, preview every script first, then apply the configuration examples in this order:

```bash
python examples/articles/logrotate/stage_logs.py --apply
python examples/articles/logrotate/install_package.py --apply
python examples/articles/logrotate/app_rule.py --apply
python examples/articles/logrotate/multi_app.py --apply
python examples/articles/logrotate/size_based.py --apply
python examples/articles/logrotate/timer_state.py --apply
python examples/articles/logrotate/inspect_logrotate.py
```

Then repeat the stateful operations. Every command below should report no changes:

```bash
# Every command below should report no changes.
python examples/articles/logrotate/stage_logs.py --apply
python examples/articles/logrotate/app_rule.py --apply
python examples/articles/logrotate/multi_app.py --apply
python examples/articles/logrotate/timer_state.py --apply
```

Two operations are deliberately excluded from that list. `install_package.py` converges too, but only after the package exists; re-run it freely. `size_based.py` reports the `logrotate.validate` request as changed on every pass by design — the stateless dry run is supposed to re-check the live host — while its `files.install` request reports no change.

Finally exercise the manual rotation and the cleanup, and prove the removal converges:

```bash
python examples/articles/logrotate/rotate_now.py --apply
python examples/articles/logrotate/inspect_logrotate.py
python examples/articles/logrotate/remove_rules.py --apply
python examples/articles/logrotate/remove_rules.py --apply
```

The second `remove_rules.py` run should report no changes: every drop-in, fixture and script is already absent. Between the rotation and the removal, `inspect_logrotate.py` shows the fresh `last_rotated` timestamps that prove the policy actually fired.

## Implementation summary

Reemote's logrotate support is three facts and four operations wrapped around one disciplined write. `LogrotateVersion`, `LogrotateConfig` and `LogrotateStatus` read the binary release, the parsed stanzas of the main configuration and every drop-in, and the per-log rotation timestamps — each in a single round trip per host. `rule` renders one drop-in from typed arguments, compares the whole text against the live file, and on a real difference spools to a private `/tmp` directory, validates the exact bytes with `logrotate -d` and installs the file `root:root` mode `0644`; `present=False` removes only the managed file. `validate` and `rotate` are stateless by design: they re-run the dry check or force a real rotation on every pass rather than pretending to converge. `service` reconciles the `logrotate.timer` unit against live systemd state.

The practical result is a workflow with no template files and no callbacks to parse: rotation policies are hashable Python arguments in ordinary loops, package installation and scheduling compose from the neighbouring `apt`, `crontab` and `openrc` modules, the preview shows the real host state each decision was made from, and a second pass produces no writes for the stateful operations. The [module reference](../modules/logrotate.md) lists the complete API, and the [examples index](../examples.md) describes the shared real-host execution contract.

## References

- [How to Manage Log Files with Logrotate on Ubuntu (Better Stack)](https://betterstack.com/community/guides/logging/how-to-manage-log-files-with-logrotate-on-ubuntu-20-04/)
- [Log rotation with Linux logrotate (Dash0)](https://www.dash0.com/guides/log-rotation-linux-logrotate)
- [Log file control with logrotate (Datadog)](https://www.datadoghq.com/blog/log-file-control-with-logrotate/)
- [Setting logrotate (Red Hat)](https://www.redhat.com/en/blog/setting-logrotate)

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

