# Managing Incus with Python

Incus is the next-generation manager for system containers and virtual machines from the Linux Containers project: it is image-based, manages whole machines rather than single application processes, and ships long-term-support releases such as Incus 6.0. Reemote is a pure-Python configuration-management library that installs packages, manages files and drives host commands over SSH without requiring Python on the managed machine. Together they let us describe an Incus server — its storage pools, networks, profiles and instances — in ordinary Python, preview the changes against the live daemon, and converge persistent hosts on the desired configuration.

## 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. The existing-container demonstration mentioned above belongs to the [Alpine walkthrough](../articles/alpine.md); here we use SSH throughout.

## Inventory for a real Incus host

Use a persistent Ubuntu 24.04 machine or VM that can host the Incus daemon. The LTS release is in the Ubuntu archive, so no extra repository is needed; `sudo -n true` must succeed for the deployment account, and system containers require no virtualisation support. The examples target Reemote's `Ubuntu` OS family.

These are persistent hosts, not containers created by the examples. The configuration scripts create storage pools, networks, profiles and instances on the daemon. A dedicated lab host avoids disturbing anyone else's workloads.

Save this as `inventory.json`, replacing the address, username and key path with your own host:

```json
[
  {
    "host": "ubuntu",
    "family": "Ubuntu",
    "connection": {
      "connector": "ssh",
      "address": "192.168.0.251",
      "username": "supervisor",
      "known_hosts": null,
      "key_path": "~/.ssh/id_ed25519"
    }
  }
]
```

This is the lab inventory from the repository root, and it is what every example below loads by default. The `"known_hosts": null` entry disables host-key checking and exists only because the lab hosts were provisioned ad hoc. On a real network, obtain the host's fingerprint through a trusted console, populate `~/.ssh/known_hosts` and delete the `known_hosts` key instead; never disable verification to bypass a mismatch. Add further Incus servers with the same shape and they are managed in lockstep.

The [SSH connector](../connectors/ssh.md) handles transport; `family`, not an inventory group, selects eligible hosts. All scripts load the inventory only when invoked, select its `Ubuntu` entries and reject container connections. Omitting `--inventory` uses the repository's root `inventory.json`.

## Runnable example index

Clone [the Reemote repository](https://github.com/kimjarvis/reemote), install its dependencies, and run the commands below from its root. Keep your inventory there, or pass an absolute path. Python runs on the controller, not on the managed machines.

```bash
git clone https://github.com/kimjarvis/reemote.git
cd reemote
uv sync --group dev
```

The complete scripts are in [`examples/articles/incus/`](https://github.com/kimjarvis/reemote/tree/main/examples/articles/incus/). Mutating scripts preview first and change hosts only with `--apply`. The inspection script is read-only. The sibling `incus_article_common.py` supplies inventory loading, family guards, CLI options and the runner.

| Example | What it demonstrates |
| --- | --- |
| [`incus_hello.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_hello.py) | The canonical two operations over persistent SSH connections |
| [`incus_bootstrap.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_bootstrap.py) | Installing Incus with `apt.packages` and initializing the daemon once |
| [`incus_pools.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_pools.py) | `incus.ensure_storage_pool` for a dedicated directory pool |
| [`incus_network.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_network.py) | `incus.ensure_network` for a private NAT bridge |
| [`incus_profile.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_profile.py) | `incus.ensure_profile` with limits and a NIC device |
| [`incus_instances.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_instances.py) | `incus.ensure_instance` launching a running container and creating a stopped one |
| [`incus_power.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_power.py) | Deliberate start and stop maintenance actions |
| [`incus_inspect.py`](https://github.com/kimjarvis/reemote/blob/main/examples/articles/incus/incus_inspect.py) | Read-only gathering of all four Incus fact groups |

Start with the SSH counterpart of the greeting example. Run it again after applying: unchanged files should produce no further write commands.

```bash
uv run python examples/articles/incus/incus_hello.py
uv run python examples/articles/incus/incus_hello.py --apply
```

## Provisioning the server, not the guests

Incus automation splits into two uses that are worth keeping apart. The first provisions the Incus server itself: packages, storage pools, networks, profiles and instances. The second reaches inside already-running instances, so commands execute in the guest.

This article covers the first use: the Incus server is an ordinary SSH host in the inventory, and its resources are declared with the [`incus` module](../modules/incus.md). Reemote never connects into the instances — guest configuration belongs to the instance itself or to a separate inventory entry for it.

The properties that shape every example below are Reemote's own: the daemon is reached over SSH and elevated per request with `sudo=True`; trust material is just the operator's SSH public key, so no daemon trust is configured; the `incus.ensure_*` operations read facts and emit only drift commands instead of running guarded shell; preview is the default and `--apply` performs the changes; and convergence is built in, so a second run sends no commands at all.

The examples use Reemote's lockstep runner: every host finishes an operation before any host advances. That is not a rolling one-host-at-a-time provisioning policy. Use a one-host inventory when a maintenance window requires that restriction.

### The Reemote Incus module

The [`incus` module](../modules/incus.md) manages the daemon's own resources. Its four facts — `IncusInstances`, `IncusStoragePools`, `IncusNetworks` and `IncusProfiles` — run the `incus` CLI with `--format json` and return name-keyed mappings of the raw records, so a deploy reasons about live state rather than assumptions. Its four operations — `ensure_storage_pool`, `ensure_network`, `ensure_profile` and `ensure_instance` — compare the requested configuration against those facts and yield commands only for drift.

Three safety properties matter on a shared server. Requests are additive: stale configuration keys and devices are reported as unchanged rather than deleted. Creation-only properties are never rewritten: an existing pool keeps its driver, an existing network keeps its type, and an existing instance keeps its image and profile list. And because instance records feed the facts, a stopped instance is a visible state, not a failure. Configuration is passed as hashable tuples — `(("limits.cpu", "2"),)` for keys and `(("eth0", (("type", "nic"), ("network", "labbr0"))),)` for devices — which keeps requests previewable in the plan.

## Install and initialize Incus

`incus_bootstrap.py` makes the lab host usable. Its deploy is a single `apt.packages` request that installs the `incus` package from the Ubuntu archive with `sudo=True`. Installing the package is not the same as initializing the daemon: before `incus admin init`, the CLI answers queries with empty collections and no storage pool exists.

After applying, the script probes each host with a read-only `incus storage list --format json` action and runs `incus admin init --minimal` only where that probe came back empty. The minimal preset creates a directory-backed storage pool named `default` and keeps the existing `default` profile, mirroring the manual steps in the [first-steps tutorial](https://linuxcontainers.org/incus/docs/main/tutorial/first_steps/). The command is a no-op on an initialized daemon, so repeating the bootstrap changes nothing:

```bash
uv run python examples/articles/incus/incus_bootstrap.py
uv run python examples/articles/incus/incus_bootstrap.py --apply
```

The probe-and-initialize step is a `gather_action` call after the deploy barrier, not an operation: it is host-local imperative logic, and Reemote keeps that separate from the declarative plan.

## Ensure a storage pool

With a daemon in place, give the lab its own pool. `incus_pools.py` ensures a directory-backed pool named `fast`:

```bash
uv run python examples/articles/incus/incus_pools.py
uv run python examples/articles/incus/incus_pools.py --apply
```

The `dir` driver is deliberately portable; it works on any filesystem, which suits a lab host without a dedicated block device. The module supports the other drivers the daemon reports, but a pool's driver is chosen at creation and the operation will never convert one in place. Passing a storage `source` for a pool that already exists with different settings raises an `OperationError` instead of guessing, so this example manages an unbacked directory pool.

## Ensure a private bridge network

`incus_network.py` creates a managed bridge named `labbr0` on a private subnet, with NAT for outbound traffic and IPv6 left off:

```bash
uv run python examples/articles/incus/incus_network.py
uv run python examples/articles/incus/incus_network.py --apply
```

The requested configuration is a tuple of pairs — `ipv4.address`, `ipv4.nat` and `ipv6.address` — and only drifted keys produce `incus network set` commands. Changing `network_type` later would not touch the existing bridge: the operation reports drift rather than destroying a network that instances may be attached to.

## Ensure a profile with limits and a device

Profiles carry the shape of a workload. `incus_profile.py` ensures a `web` profile with a CPU limit, an ownership annotation, and an `eth0` NIC attached to the lab bridge:

```bash
uv run python examples/articles/incus/incus_profile.py
uv run python examples/articles/incus/incus_profile.py --apply
```

A missing profile is created first, then each requested key is set and each missing device added. Existing devices are reconciled property by property; the device `type` is part of the request but is never rewritten, and devices nobody asked for remain in place. Apply the network example before this one so the NIC's target bridge exists.

## Launch instances

The lab's workload is two containers from the same image: a running web server built on the profile, and a stopped batch container created for later. `incus_instances.py` expresses both as `ensure_instance` requests:

```python
# incus_instances.py: deploy
def deploy(host):
    yield op(
        incus.ensure_instance,
        name="Ensure web instance",
        instance_name=WEB,
        image=IMAGE,
        profiles=("default", "web"),
        config=(("limits.memory", "1GiB"),),
        running=True,
        sudo=True,
        when=is_ubuntu,
    )
    yield op(
        incus.ensure_instance,
        name="Ensure batch instance",
        instance_name=BATCH,
        image=IMAGE,
        profiles=("default",),
        config=(("user.note", "created stopped"),),
        running=False,
        sudo=True,
        when=is_ubuntu,
    )
```

`IMAGE` is `images:ubuntu/24.04`, an alias on the images remote that the daemon resolves to the current Ubuntu 24.04 container image. A missing instance with `running=True` is created with `incus launch`; one with `running=False` uses `incus init`, so it is configured but stays stopped. An existing instance keeps its image and profile list whatever the request says — only the requested configuration keys and the power state are reconciled.

```bash
uv run python examples/articles/incus/incus_instances.py
uv run python examples/articles/incus/incus_instances.py --apply
```

The first apply downloads the image, launches `web01` and initializes `batch01`. A second apply reads the facts, finds no drift and sends no commands.

## Start and stop deliberately

Power changes are maintenance actions, not convergence noise. `incus_power.py` takes an explicit `start` or `stop` argument and reconciles only the runtime state of the `web01` instance from the previous example:

```bash
uv run python examples/articles/incus/incus_power.py stop
uv run python examples/articles/incus/incus_power.py start
```

Both commands preview; add `--apply` to the action you intend to perform. An unsupported action raises before anything connects. Keep these out of the convergence sequence below: `incus_instances.py` declares `web01` running, so a scripted stop would be undone by the next convergent run — which is exactly the behaviour you want once the desired state is owned by a deploy.

## Inspect and prove convergence

`incus_inspect.py` is read-only. It gathers the four Incus facts concurrently across the hosts, prints instances with their status plus the sorted pool, network and profile names, and closes every connection even when a read fails. The `--check` option exits nonzero until the host carries the complete lab: the `fast` pool, the `labbr0` bridge, the `web` profile and a running `web01`.

To establish the lab from a fresh Incus host, use this sequence after reviewing the corresponding previews:

<!-- initial-workflow -->
```bash
uv run python examples/articles/incus/incus_bootstrap.py --apply
uv run python examples/articles/incus/incus_pools.py --apply
uv run python examples/articles/incus/incus_network.py --apply
uv run python examples/articles/incus/incus_profile.py --apply
uv run python examples/articles/incus/incus_instances.py --apply
uv run python examples/articles/incus/incus_inspect.py --check
```

Repeat the whole sequence to prove convergence:

<!-- converged-workflow -->
```bash
uv run python examples/articles/incus/incus_bootstrap.py --apply
uv run python examples/articles/incus/incus_pools.py --apply
uv run python examples/articles/incus/incus_network.py --apply
uv run python examples/articles/incus/incus_profile.py --apply
uv run python examples/articles/incus/incus_instances.py --apply
uv run python examples/articles/incus/incus_inspect.py --check
```

With unchanged inputs and host state, this repeat sends no mutating deployment commands: the package is installed, every pool, network, profile and instance already exists as configured, and the probe reports the daemon as initialized. It is configuration convergence, not a promise that instance metrics or image cache sizes stop changing.

The offline suite executes the canonical snippet, every indexed example and these exact workflow sequences on persistent simulated hosts. It covers preview safety, family selection, initialization probing, additive reconciliation, power semantics, inspection cleanup and second-pass convergence:

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

Simulation does not run a real Incus daemon or prove image availability. The indexed scripts are the real-host counterparts, and they were verified live against an Ubuntu 24.04 host running Incus 6.0 LTS: each example's preview, apply and convergent second pass produced the commands described above.

## Further information

- The [Incus introduction](https://linuxcontainers.org/incus/introduction/) describes the project's scope and release model.
- The [announcement post](https://stgraber.org/2023-10-11/introducing-incus/) explains where Incus came from and how it is governed.
- The [first-steps tutorial](https://linuxcontainers.org/incus/docs/main/tutorial/first_steps/) covers the interactive equivalent of everything this article automates.
- Reemote's own references: the [incus module](../modules/incus.md), the [SSH connector](../connectors/ssh.md) and the [Alpine walkthrough](../articles/alpine.md) for the canonical example's origin.

## Implementation summary

The install/provision workflow is now a set of ordinary Python programs targeting the `Ubuntu` OS family. `apt.packages` provisions the daemon package and a post-deploy probe initializes it once; the four `incus.ensure_*` operations reconcile storage pools, networks, profiles and instances against live facts, emitting only drift commands while never deleting unrequested keys or rewriting creation-time properties; explicit power actions stay separate from convergent deploys; and the fact-gathering inspector proves the end state. The same SSH host retains its daemon configuration across runs, and the article's pytest suite checks that the final deployment converges without a single mutating command.

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

