Author SHA1 Message Date
Defame1297 c109d24229 ci(molecule): name the issue that removes the docker CLI mount
Build / build (pull_request) Successful in 38s
Molecule / molecule (pull_request) In progress
Lint / lint (pull_request) Successful in 3m24s
Part of #455

Assisted-by: Claude Code
2026-11-28 16:27:24 +00:00
Defame1297 faf1c7e36f ci(molecule): connect over the Docker API with a fixed Python interpreter
The docker driver's community.docker.docker connection starts the docker CLI for every task
on every host, and each playbook run discovers the interpreter on every container although
both molecule images ship /usr/bin/python3. The shared base config now sets
provisioner.connection_options, which molecule merges over the driver's own connection vars
for the container hosts only, so localhost keeps the controller's Python.

community.docker 5.4.1's docker_api connection supports pipelining and become and needs only
requests, which requirements-dev.lock already pins. The docker CLI bind mount in molecule.yml
stays until a green run shows nothing needs it; its comment and two others that named the
CLI's calls now describe the API connection.

Closes #455

Assisted-by: Claude Code
2026-11-28 15:51:17 +00:00
Defame1297 b5a5a4efa1 Merge pull request 'ci(molecule): start the longest scenarios first and pass the lane count in' (#461) from ci/432-molecule-order-lanes into main
Reviewed-on: #461
Reviewed-by: Defame1297 <[email protected]>
2026-11-28 15:01:59 +00:00
Defame1297 c0c1485470 Merge branch 'main' into ci/432-molecule-order-lanes
Build / build (pull_request) Successful in 29s
Lint / lint (pull_request) Successful in 4m8s
Molecule / molecule (pull_request) Successful in 38m42s
2026-11-28 14:22:43 +00:00
Defame1297 92cf7257d4 test(molecule): wrap the runner stub under the sanity line limit
Build / build (pull_request) Successful in 30s
Lint / lint (pull_request) Successful in 3m51s
Molecule / molecule (pull_request) Successful in 34m54s
Part of #432

Assisted-by: Claude Code
2026-11-28 08:48:29 +00:00
Defame1297 e34a0eb2e0 test(molecule): derive the order test from the duration list
Part of #432. The start-order test now reads its scenarios and their seconds
from the run script's list, so a refreshed list does not break it; the
empty-lanes test only asserts the value is accepted, and the script's header
and duration-list comments are rewrapped and say the list is keyed by
scenario directory.

Assisted-by: Claude Code
2026-11-28 08:45:05 +00:00
Defame1297 ef840c8952 ci(molecule): start the longest scenarios first and pass the lane count in
Part of #432. A long scenario started late sets the end of a full run, so
run_molecule_scenarios.sh now starts scenarios by the durations of the last
full run, longest first, with an unlisted scenario first; the log groups keep
the selection order. A workflow_dispatch input `lanes` reaches the script as
MOLECULE_LANES, so full runs with different lane counts can be compared; an
empty value keeps the default of 4.

The shared molecule config enables ansible.posix.profile_tasks (summary only)
and ansible.posix.timer, so each scenario's log shows where its time goes.

Assisted-by: Claude Code
2026-11-28 08:36:20 +00:00
Defame1297 29db4985fe Merge pull request 'feat(nfs_client): add a role that manages NFS client entries in fstab' (#451) from feat/402-nfs-client into main
Reviewed-on: #451
2026-11-28 08:25:06 +00:00
Defame1297 1fedced1d3 Merge branch 'main' into feat/402-nfs-client
Build / build (pull_request) Successful in 30s
Molecule / molecule (pull_request) Successful in 1m42s
Lint / lint (pull_request) Successful in 2m29s
2026-11-28 08:22:32 +00:00
Defame1297 a2ab13a6e1 Merge pull request 'feat(docker): pin the Docker apt key by checksum' (#454) from feat/448-docker-keyring-checksum into main
Reviewed-on: #454
2026-11-28 08:22:23 +00:00
Defame1297 a185a301db docs(docker): say the keyring checksum follows an overridden key URL
Build / build (pull_request) Successful in 28s
Lint / lint (pull_request) Successful in 3m37s
Molecule / molecule (pull_request) Successful in 7m29s
Set docker_keyring_checksum together with docker_gpg_url, and state that
the checksum is the hex digest without the sha256: prefix.

Assisted-by: Claude Code
2026-11-27 22:25:00 +00:00
Defame1297 c7c38c6bc0 feat(docker): pin the Docker apt key by checksum
The key that signs the Docker repository was trusted as whatever the URL served. It is now checked
against a pinned sha256, so a changed key stops the install until a person has verified it.

Assisted-by: Claude Code
2026-11-27 22:09:56 +00:00
Dragonish fcd2290e14 test(nfs_client): refresh the apt cache in the scenario's prepare
Build / build (pull_request) Successful in 31s
Molecule / molecule (pull_request) Successful in 2m5s
Lint / lint (pull_request) Successful in 2m47s
The molecule image ships without apt lists, and --check does not refresh
them, so the fresh-host check found no nfs-common to install and failed
with "No package matching 'nfs-common' is available". The docker, pihole,
system_baseline and traefik scenarios refresh the cache in prepare for the
same reason.

Refs #402

Assisted-by: Claude Code
2026-11-27 21:55:02 +00:00
Dragonish 5ce5e3c932 feat(nfs_client): add a role that manages NFS client entries in fstab
Build / build (pull_request) Successful in 31s
Molecule / molecule (pull_request) Failing after 43s
Lint / lint (pull_request) Successful in 1m53s
Installs nfs-common and manages NFS mount entries from nfs_client_mounts
(src, path, optional opts, state present or absent). Each mount point is
created without owner, group or mode, because once a share is mounted a
chown or chmod there changes the permissions on the NFS server. The role
writes only the fstab line and reloads systemd; it never mounts or
unmounts. An absent entry maps to ansible.posix.mount's absent_from_fstab,
which removes the line and leaves the share and the directory alone.

The default options are _netdev,nofail. x-systemd.automount is left out.

Verified locally: yamllint, ansible-lint (production profile), syntax check
of the scenario playbooks, the controller-side refusals of verify.yml (14
cases, each matched on its own message), and the module's fstab behaviour
against a scratch fstab (replacement, absent_from_fstab, idempotence).
Not verified: Molecule, which runs only in CI; the apt install and the
daemon-reload handler; that systemd generates the mount units in the
scenario's containers.

Refs #402

Assisted-by: Claude Code
2026-11-27 21:47:09 +00:00
31 changed files with 921 additions and 19 deletions

No files matched your search

+15 -2
View File
@@ -3,11 +3,24 @@
# first on ANSIBLE_COLLECTIONS_PATH, so molecule's per-scenario install is unused. # first on ANSIBLE_COLLECTIONS_PATH, so molecule's per-scenario install is unused.
prerun: false prerun: false
provisioner: provisioner:
# Merged over the docker driver's own connection vars, for the container hosts only: localhost
# keeps the controller's connection and Python.
connection_options:
# Talk to the daemon over its socket, instead of starting the docker CLI for every task.
ansible_connection: community.docker.docker_api
# Both molecule images ship it; a fixed path skips interpreter discovery in every playbook run.
ansible_python_interpreter: /usr/bin/python3
config_options: config_options:
connection: connection:
# Pipe each module over stdin: without it every task pays extra docker exec and docker cp # Pipe each module over stdin: without it every task pays extra exec and copy calls to the
# calls to make a temp dir, copy the module in and clean up. # daemon to make a temp dir, copy the module in and clean up.
pipelining: true pipelining: true
defaults: defaults:
# Gather each host's facts once per playbook run, not in every play. # Gather each host's facts once per playbook run, not in every play.
gathering: smart gathering: smart
# Per-task timings, to see what a scenario's time goes to; ansible.posix is in the ci image
# and in requirements.yml, so the controller always has these callbacks.
callbacks_enabled: ansible.posix.profile_tasks, ansible.posix.timer
callback_profile_tasks:
summary_only: true
task_output_limit: 20
+8 -3
View File
@@ -110,9 +110,14 @@ issue.
concurrency group of its own.** Runs may overlap on the runner's Docker daemon: every container concurrency group of its own.** Runs may overlap on the runner's Docker daemon: every container
is named and labelled by its run (`KAMINO_RUN_ID`). The job first removes labelled containers is named and labelled by its run (`KAMINO_RUN_ID`). The job first removes labelled containers
older than its timeout, which a cancelled run left, and finally its own. The scenarios of one older than its timeout, which a cancelled run left, and finally its own. The scenarios of one
run overlap (`scripts/run_molecule_scenarios.sh`, `MOLECULE_LANES` at a time), so no two run overlap (`scripts/run_molecule_scenarios.sh`, `MOLECULE_LANES` at a time, 4 unless a manual
scenarios may share a platform name. *Why:* a cancelled run is killed before it can remove its dispatch sets its `lanes` input), so no two scenarios may share a platform name. They start
instances, and a younger container may belong to a run still going. *Held:* review; control: longest first by the script's list of last full-run times, an unlisted one first; the logs stay
in selection order. *Why:* a cancelled run is killed before it can remove its instances, a
younger container may belong to a run still going, and a long scenario started late sets the
end of the run. *Held:* review; control: the start order by
`test_the_longest_scenarios_start_first` and the input by `LanesInputTest`, both in
`tests/scripts/test_run_molecule_scenarios.py`; control:
the names and labels by the test the `test_sequence` rule below names, and the sweep's age bound the names and labels by the test the `test_sequence` rule below names, and the sweep's age bound
equal to the job timeout by `test_the_sweep_spares_containers_younger_than_the_job_timeout` in equal to the job timeout by `test_the_sweep_spares_containers_younger_than_the_job_timeout` in
`tests/scripts/test_run_molecule_scenarios.py`. `tests/scripts/test_run_molecule_scenarios.py`.
+13 -4
View File
@@ -24,7 +24,13 @@ on: # yamllint disable-line rule:truthy
# drift in the others (a package mirror) would otherwise go unseen. After Renovate's 03:17 run. # drift in the others (a package mirror) would otherwise go unseen. After Renovate's 03:17 run.
schedule: schedule:
- cron: "43 4 * * *" - cron: "43 4 * * *"
workflow_dispatch: {} workflow_dispatch:
inputs:
lanes:
description: Scenarios run at a time (empty for the default of run_molecule_scenarios.sh)
required: false
type: string
default: ""
permissions: permissions:
contents: read contents: read
@@ -123,6 +129,8 @@ jobs:
EVENT_NAME: ${{ github.event_name }} EVENT_NAME: ${{ github.event_name }}
# The workflow only runs for pull requests to main; lint.yml uses the same constant. # The workflow only runs for pull requests to main; lint.yml uses the same constant.
BASE_REF: origin/main BASE_REF: origin/main
# Empty outside a dispatch, which the run script reads as its default.
MOLECULE_LANES: ${{ inputs.lanes }}
run: | run: |
# The selector comes from the base branch, so a pull request cannot edit the rules it is # The selector comes from the base branch, so a pull request cannot edit the rules it is
# judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that # judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that
@@ -140,8 +148,9 @@ jobs:
# As the runner user, with the socket's group, so nothing in the job tree is left root-owned. # As the runner user, with the socket's group, so nothing in the job tree is left root-owned.
# HOME (ansible's temp and caches) is in the job tree; a mounted passwd entry points the user # HOME (ansible's temp and caches) is in the job tree; a mounted passwd entry points the user
# at it, because ansible's temp path is `~<user>/.ansible/tmp`. The driver's connection plugin # at it, because ansible's temp path is `~<user>/.ansible/tmp`. The image lacks the docker CLI
# (community.docker.docker) runs the docker CLI, which the image lacks: the host's goes in. # and the scenarios connect over the socket (docker_api); the host's CLI goes in until #462
# removes it.
ac_root="$(cd ../../.. && pwd)" ac_root="$(cd ../../.. && pwd)"
sock_gid="$(stat -c %g /var/run/docker.sock)" sock_gid="$(stat -c %g /var/run/docker.sock)"
docker_cli="$(readlink -f "$(command -v docker)")" docker_cli="$(readlink -f "$(command -v docker)")"
@@ -154,7 +163,7 @@ jobs:
-v /var/run/docker.sock:/var/run/docker.sock -v "$docker_cli:/usr/local/bin/docker:ro" \ -v /var/run/docker.sock:/var/run/docker.sock -v "$docker_cli:/usr/local/bin/docker:ro" \
-v "$ac_root:$ac_root" -v "$ac_root/passwd:/etc/passwd:ro" -w "$PWD" \ -v "$ac_root:$ac_root" -v "$ac_root/passwd:/etc/passwd:ro" -w "$PWD" \
-e "AC_ROOT=$ac_root" -e "HOME=$ac_root/home" -e "USER=$(id -un)" \ -e "AC_ROOT=$ac_root" -e "HOME=$ac_root/home" -e "USER=$(id -un)" \
-e MOLECULE_IMAGE -e MOLECULE_IMAGE_2604 -e KAMINO_RUN_ID \ -e MOLECULE_IMAGE -e MOLECULE_IMAGE_2604 -e KAMINO_RUN_ID -e MOLECULE_LANES \
"$CI_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$selected" "$CI_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$selected"
# A cancelled run can leave its containers running when the docker client is killed. # A cancelled run can leave its containers running when the docker client is killed.
+1 -1
View File
@@ -2,7 +2,7 @@
An Ansible Collection of reusable, hardened roles for a self-hosted home lab: An Ansible Collection of reusable, hardened roles for a self-hosted home lab:
`cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`,
`pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `nfs_client`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and
`user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap). `user_management`, plus the internal `_binary_update`. Roles still to come are listed under [Roadmap](#roadmap).
Status: roles arrive in waves. Release 3.2.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call). Status: roles arrive in waves. Release 3.2.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `tailscale`, `traefik`, `ufw` and `user_management` roles (and the internal `_binary_update`, which `cloudflared`, `gitea`, `gitea_runner` and `traefik` call).
+8
View File
@@ -0,0 +1,8 @@
---
minor_changes:
- >-
nfs_client - New role. Installs ``nfs-common`` and manages NFS mount entries in ``/etc/fstab`` from ``nfs_client_mounts``
(``src``, ``path``, optional ``opts`` and ``state`` ``present`` or ``absent``), with ``nfs_client_default_opts``
(default ``_netdev,nofail``) for an entry that sets none. It creates each mount point without owner, group or mode,
writes only the fstab line, never mounts or unmounts, and reloads systemd after a change. An ``absent`` entry loses its
line and nothing else. Declares Ubuntu noble and resolute; the molecule scenario never mounts a share.
@@ -0,0 +1,6 @@
---
minor_changes:
- >-
docker - New input ``docker_keyring_checksum``: the Docker APT key is verified against a pinned
sha256, and a changed key fails the install until a person has checked it and updated the hash.
Set ``docker_keyring_checksum`` too when ``docker_gpg_url`` is overridden.
+2 -2
View File
@@ -7,7 +7,7 @@ authors:
- Defame1297 - Defame1297
description: >- description: >-
Reusable, hardened Ansible roles for a self-hosted home lab (cloudflared, docker, fail2ban, Reusable, hardened Ansible roles for a self-hosted home lab (cloudflared, docker, fail2ban,
gitea, gitea_runner, network_interfaces, pihole, pve_lxc, sshd, system_baseline, gitea, gitea_runner, network_interfaces, nfs_client, pihole, pve_lxc, sshd, system_baseline,
systemd_hardening, tailscale, traefik, ufw, user_management; _binary_update is internal). systemd_hardening, tailscale, traefik, ufw, user_management; _binary_update is internal).
license: license:
- GPL-3.0-or-later - GPL-3.0-or-later
@@ -22,7 +22,7 @@ homepage: https://git.rkdr.net/mortis/kamino
issues: https://git.rkdr.net/mortis/kamino/issues issues: https://git.rkdr.net/mortis/kamino/issues
# CI tests the versions pinned in requirements.yml; the lower bounds here are not tested. # CI tests the versions pinned in requirements.yml; the lower bounds here are not tested.
# No upper bound, so a consumer's newer pin does not conflict. community.general is used by system_baseline and ufw, # No upper bound, so a consumer's newer pin does not conflict. community.general is used by system_baseline and ufw,
# ansible.posix by system_baseline and user_management, community.proxmox by pve_lxc (Proxmox VE guest lifecycle). # ansible.posix by nfs_client, system_baseline and user_management, community.proxmox by pve_lxc (Proxmox VE guest lifecycle).
# community.proxmox's modules import the Python library proxmoxer (2.3 or later) on the controller; galaxy.yml # community.proxmox's modules import the Python library proxmoxer (2.3 or later) on the controller; galaxy.yml
# cannot declare a Python dependency, so the README says it and requirements-dev.txt pins it for CI. # cannot declare a Python dependency, so the README says it and requirements-dev.txt pins it for CI.
dependencies: dependencies:
+4 -2
View File
@@ -27,6 +27,7 @@ The role targets Ubuntu hosts only: it installs from Docker's Ubuntu repository,
| `docker_keyring_path` | `/etc/apt/keyrings/docker.asc` | no | Repository key location. | | `docker_keyring_path` | `/etc/apt/keyrings/docker.asc` | no | Repository key location. |
| `docker_apt_list_path` | `/etc/apt/sources.list.d/docker.list` | no | APT source file. | | `docker_apt_list_path` | `/etc/apt/sources.list.d/docker.list` | no | APT source file. |
| `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. | | `docker_gpg_url` | `https://download.docker.com/linux/ubuntu/gpg` | no | Key URL. |
| `docker_keyring_checksum` | sha256 of the current Docker key | no | Expected sha256 (hex, no `sha256:` prefix) of the key at `docker_gpg_url`; set it too when `docker_gpg_url` is overridden; a mismatch fails the download, so a changed key stops the install until this is updated. |
| `docker_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. | | `docker_repo_base_url` | `https://download.docker.com/linux/ubuntu` | no | Repository base URL. |
| `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. | | `docker_apt_arch` | derived from the host | no | Architecture in the APT source. Empty derives it (`x86_64` gives `amd64`, `aarch64` gives `arm64`); another architecture fails until this is set. A value set here is always used; lowercase letters and digits only. |
| `docker_start_missed` | `false` | no | Install a boot unit that starts the containers Docker skipped after a reboot (see [Boot and shutdown units](#boot-and-shutdown-units)). | | `docker_start_missed` | `false` | no | Install a boot unit that starts the containers Docker skipped after a reboot (see [Boot and shutdown units](#boot-and-shutdown-units)). |
@@ -86,17 +87,18 @@ With any of `docker_daemon_options`, `docker_live_restore`, `docker_log_driver`,
## Tests ## Tests
`molecule/default` runs in CI only (`.gitea/workflows/molecule.yml`, no local runner), on two platforms: `${MOLECULE_IMAGE}` (Ubuntu 24.04) and `${MOLECULE_IMAGE_2604}` (Ubuntu 26.04). A real Docker Engine cannot run there: `dockerd` needs the bridge, iptables rules and a delegated cgroup, and the container has no privileged mode. So the scenario builds a local APT repository, signs it with a throwaway key, and points the role at it with `docker_gpg_url` and `docker_repo_base_url`. The repository holds empty stand-ins for `docker-ce`, `docker-ce-cli` and `containerd.io`. The stand-in `docker-ce` ships a stub `docker.service` (`sleep infinity`) and creates the `docker` group, as the real package does. It runs `check` before the converge (on a fresh host) and after it (on the configured host). `molecule/default` runs in CI only (`.gitea/workflows/molecule.yml`, no local runner), on two platforms: `${MOLECULE_IMAGE}` (Ubuntu 24.04) and `${MOLECULE_IMAGE_2604}` (Ubuntu 26.04). A real Docker Engine cannot run there: `dockerd` needs the bridge, iptables rules and a delegated cgroup, and the container has no privileged mode. So the scenario builds a local APT repository, signs it with a throwaway key, and points the role at it with `docker_gpg_url`, `docker_keyring_checksum` (the throwaway key's hash) and `docker_repo_base_url`. The repository holds empty stand-ins for `docker-ce`, `docker-ce-cli` and `containerd.io`. The stand-in `docker-ce` ships a stub `docker.service` (`sleep infinity`) and creates the `docker` group, as the real package does. It runs `check` before the converge (on a fresh host) and after it (on the configured host).
What it shows, with the role's tasks running unchanged: What it shows, with the role's tasks running unchanged:
- The key is fetched, stored at `docker_keyring_path` with mode `0644`, and apt really verifies the repository against it (an unsigned or wrongly signed repository would leave no install candidate). - The key is fetched, checked against `docker_keyring_checksum`, stored at `docker_keyring_path` with mode `0644`, and apt really verifies the repository against it (an unsigned or wrongly signed repository would leave no install candidate).
- The source line has the architecture, the `signed-by` keyring and `ansible_facts['distribution_release']`. - The source line has the architecture, the `signed-by` keyring and `ansible_facts['distribution_release']`.
- The packages are installed from that repository, the unit is enabled and active, and `docker_users` join `docker_group`. - The packages are installed from that repository, the unit is enabled and active, and `docker_users` join `docker_group`.
- `docker_remove` with `docker_remove_data` removes the source line, the keyring, the packages, the unit and `/var/lib/docker`. - `docker_remove` with `docker_remove_data` removes the source line, the keyring, the packages, the unit and `/var/lib/docker`.
- Both units are installed, enabled, ordered against `docker.service` as stated, the shutdown unit is active, a unit is removed when its input is `false`, and `docker_remove` removes both. - Both units are installed, enabled, ordered against `docker.service` as stated, the shutdown unit is active, a unit is removed when its input is `false`, and `docker_remove` removes both.
- With the daemon inputs set, `/etc/docker/daemon.json` is valid JSON with exactly the expected keys, mode `0644` and root-owned. A change with `docker_daemon_restart: false` leaves dockerd running (its start time is unchanged); with `true` it restarts it. A key set both in `docker_daemon_options` and by a dedicated input, and a bad log size, driver or file count, are refused before any change. - With the daemon inputs set, `/etc/docker/daemon.json` is valid JSON with exactly the expected keys, mode `0644` and root-owned. A change with `docker_daemon_restart: false` leaves dockerd running (its start time is unchanged); with `true` it restarts it. A key set both in `docker_daemon_options` and by a dedicated input, and a bad log size, driver or file count, are refused before any change.
- The argument check refuses a mapping for `docker_users`, a non-boolean `docker_remove` and a `docker_stop_at_shutdown_timeout` of 0. - The argument check refuses a mapping for `docker_users`, a non-boolean `docker_remove` and a `docker_stop_at_shutdown_timeout` of 0.
- A key whose hash does not match `docker_keyring_checksum` fails the key download.
- A second run changes nothing (molecule's idempotence check). - A second run changes nothing (molecule's idempotence check).
What it does not show: what the units do at a real boot or shutdown (the container has no dockerd, no NFS shares and no reboot; the selection logic of `docker-start-missed` is unit-tested in `tests/scripts/test_docker_files.py`), that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role. What it does not show: what the units do at a real boot or shutdown (the container has no dockerd, no NFS shares and no reboot; the selection logic of `docker-start-missed` is unit-tested in `tests/scripts/test_docker_files.py`), that the upstream repository and key at `download.docker.com` are reachable and valid, that the real packages install, that `dockerd` starts, anything about container networking or iptables, the `docker_update` path (`tasks/update.yml`), and removal without `docker_remove_data` (the removal stops the unit first, so it can run only once per install). It needs the Ubuntu mirrors, for the `curl` the role installs. These gaps are a known residual risk of the role.
+4
View File
@@ -11,6 +11,10 @@ docker_packages:
docker_keyring_path: /etc/apt/keyrings/docker.asc docker_keyring_path: /etc/apt/keyrings/docker.asc
docker_apt_list_path: /etc/apt/sources.list.d/docker.list docker_apt_list_path: /etc/apt/sources.list.d/docker.list
docker_gpg_url: https://download.docker.com/linux/ubuntu/gpg docker_gpg_url: https://download.docker.com/linux/ubuntu/gpg
# sha256 of Docker's package signing key (9DC858229FC7DD38854AE2D88D81803C0EBFCD88), as the ASCII-armored file
# docker_gpg_url serves. Static on purpose: a rotated or re-armored key fails the install until a person has checked the
# new one and updated this hash.
docker_keyring_checksum: "1500c1f56fa9e26b9b8f42452a553675796ade0807cdce11975eb98170b3a570"
docker_repo_base_url: https://download.docker.com/linux/ubuntu docker_repo_base_url: https://download.docker.com/linux/ubuntu
# Architecture written into the APT source. Empty (the default) derives it from the host: x86_64 gives amd64, aarch64 gives arm64, any # Architecture written into the APT source. Empty (the default) derives it from the host: x86_64 gives amd64, aarch64 gives arm64, any
+8
View File
@@ -49,6 +49,14 @@ argument_specs:
default: https://download.docker.com/linux/ubuntu/gpg default: https://download.docker.com/linux/ubuntu/gpg
description: description:
- URL of the repository signing key. - URL of the repository signing key.
docker_keyring_checksum:
type: str
default: 1500c1f56fa9e26b9b8f42452a553675796ade0807cdce11975eb98170b3a570
description:
- >-
sha256 of the key at C(docker_gpg_url), as the hex digest without the C(sha256:) prefix. The download fails
on a mismatch, so a rotated or re-armored upstream key stops the install until the new key is checked and
the hash updated. Set C(docker_keyring_checksum) too when C(docker_gpg_url) is overridden.
docker_repo_base_url: docker_repo_base_url:
type: str type: str
default: https://download.docker.com/linux/ubuntu default: https://download.docker.com/linux/ubuntu
@@ -7,6 +7,8 @@
hosts: all hosts: all
vars: vars:
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
# The stand-in key is generated per run, so its hash is read here rather than pinned.
docker_keyring_checksum: "{{ docker_stub_key.stat.checksum }}"
docker_repo_base_url: file:///srv/docker-stub-repo docker_repo_base_url: file:///srv/docker-stub-repo
docker_users: [moleculeuser] docker_users: [moleculeuser]
docker_start_missed: true docker_start_missed: true
@@ -18,5 +20,11 @@
docker_log_max_file: "3" docker_log_max_file: "3"
docker_daemon_options: docker_daemon_options:
max-concurrent-downloads: 3 max-concurrent-downloads: 3
pre_tasks:
- name: Stat the stand-in repository key
ansible.builtin.stat:
path: /srv/docker-stub-repo/docker.asc
checksum_algorithm: sha256
register: docker_stub_key
roles: roles:
- role: mortis.kamino.docker - role: mortis.kamino.docker
@@ -0,0 +1,27 @@
---
# The zeroed hash matches no file, so the key task must be the one that fails.
- name: Run the role with a checksum the stand-in key does not have
block:
- name: Include the role
ansible.builtin.include_role:
name: mortis.kamino.docker
vars:
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
docker_repo_base_url: file:///srv/docker-stub-repo
docker_keyring_path: /tmp/docker-refused-key.asc
docker_keyring_checksum: "{{ '0' * 64 }}"
- name: Fail when the wrong key was accepted
ansible.builtin.fail:
msg: MOLECULE-ACCEPTED
rescue:
- name: The key download stopped the play
ansible.builtin.assert:
that:
- ansible_failed_task.name == 'Install Docker APT GPG key'
- "'did not match' in ansible_failed_result.msg | default('')"
quiet: true
always:
- name: Remove the refused key path
ansible.builtin.file:
path: /tmp/docker-refused-key.asc
state: absent
+22
View File
@@ -302,12 +302,19 @@
hosts: all hosts: all
vars: vars:
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
docker_keyring_checksum: "{{ docker_stub_key.stat.checksum }}"
docker_repo_base_url: file:///srv/docker-stub-repo docker_repo_base_url: file:///srv/docker-stub-repo
docker_users: [moleculeuser] docker_users: [moleculeuser]
docker_start_missed: false docker_start_missed: false
docker_stop_at_shutdown: true docker_stop_at_shutdown: true
docker_stop_at_shutdown_timeout: 20 docker_stop_at_shutdown_timeout: 20
tasks: tasks:
- name: Stat the stand-in repository key
ansible.builtin.stat:
path: /srv/docker-stub-repo/docker.asc
checksum_algorithm: sha256
register: docker_stub_key
- name: Apply the role with the boot unit off - name: Apply the role with the boot unit off
ansible.builtin.include_role: ansible.builtin.include_role:
name: mortis.kamino.docker name: mortis.kamino.docker
@@ -368,6 +375,7 @@
hosts: all hosts: all
vars: vars:
docker_gpg_url: file:///srv/docker-stub-repo/docker.asc docker_gpg_url: file:///srv/docker-stub-repo/docker.asc
docker_keyring_checksum: "{{ docker_stub_key.stat.checksum }}"
docker_repo_base_url: file:///srv/docker-stub-repo docker_repo_base_url: file:///srv/docker-stub-repo
docker_users: [moleculeuser] docker_users: [moleculeuser]
docker_start_missed: true docker_start_missed: true
@@ -378,6 +386,12 @@
docker_log_max_file: "3" docker_log_max_file: "3"
docker_live_restore: true docker_live_restore: true
tasks: tasks:
- name: Stat the stand-in repository key
ansible.builtin.stat:
path: /srv/docker-stub-repo/docker.asc
checksum_algorithm: sha256
register: docker_stub_key
- name: Read the start time of the service - name: Read the start time of the service
ansible.builtin.command: systemctl show -p ActiveEnterTimestampMonotonic docker.service # noqa: command-instead-of-module ansible.builtin.command: systemctl show -p ActiveEnterTimestampMonotonic docker.service # noqa: command-instead-of-module
register: docker_verify_before register: docker_verify_before
@@ -420,6 +434,14 @@
- (docker_verify_daemon_after.content | b64decode | from_json)['max-concurrent-downloads'] == 6 - (docker_verify_daemon_after.content | b64decode | from_json)['max-concurrent-downloads'] == 6
quiet: true quiet: true
# A key that does not match docker_keyring_checksum fails at the key download, so the source line and packages are untouched. It goes to a separate path, so
# the installed key stays for the removal below.
- name: A key that does not match the pinned checksum is refused
hosts: all
tasks:
- name: Apply the role with a wrong checksum
ansible.builtin.include_tasks: tasks/refuse_checksum.yml
# docker_remove_data is set, so this also covers the destructive path: the packages are # docker_remove_data is set, so this also covers the destructive path: the packages are
# purged and /var/lib/docker, seeded in prepare.yml, is deleted. The removal stops the unit # purged and /var/lib/docker, seeded in prepare.yml, is deleted. The removal stops the unit
# before the package takes it away, so it can only run once; a second run would fail on the # before the package takes it away, so it can only run once; a second run would fail on the
+1
View File
@@ -23,6 +23,7 @@
ansible.builtin.get_url: ansible.builtin.get_url:
url: "{{ docker_gpg_url }}" url: "{{ docker_gpg_url }}"
dest: "{{ docker_keyring_path }}" dest: "{{ docker_keyring_path }}"
checksum: "sha256:{{ docker_keyring_checksum }}"
mode: "0644" mode: "0644"
tags: [docker, install] tags: [docker, install]
+74
View File
@@ -0,0 +1,74 @@
# nfs_client
Installs the NFS client (`nfs-common`) and manages NFS mount entries in `/etc/fstab`. It writes the fstab line, creates the mount point and reloads systemd; it never mounts or unmounts anything. Variables and their types are defined in [`meta/argument_specs.yml`](meta/argument_specs.yml), which is the source of truth.
## Supported platforms
Ubuntu 24.04 (noble) and 26.04 (resolute), the platforms the molecule scenario runs on. The role asserts a Debian-family host before any change.
Untested platforms: Debian 13 (trixie). The role has no OS-specific branch, but no scenario runs on it until the Debian image (#226) exists.
## Requirements and run order
- Use it by its fully qualified name, `mortis.kamino.nfs_client`, in a play that gathers facts: the Debian-family assert reads them.
- Role dependencies: none. The role calls `ansible.posix.mount`, so the Collection's `ansible.posix` dependency applies.
- `become` is used for every task that changes the host.
- The role does not set up an NFS server, autofs, CIFS/SMB or Kerberos, and it does not wait for a mount.
## Role variables
| Variable | Default | Description |
|---|---|---|
| `nfs_client_mounts` | `[]` | The mounts to manage: a list of entries, each mount point once. With no entries only the client package is installed. |
| `nfs_client_default_opts` | `_netdev,nofail` | Options for an entry that sets none. |
An entry takes these keys:
| Key | Default | Description |
|---|---|---|
| `src` | required | The export as `server:/export`, one word without spaces. |
| `path` | required | The mount point: absolute, without spaces, not `/`, no trailing slash. |
| `opts` | `nfs_client_default_opts` | The fstab options, one comma-separated word. Put the NFS version here, for example `vers=4.2`. |
| `state` | `present` | `present` writes the fstab line. `absent` removes it and nothing else. |
## Tags
- `nfs_client`: everything the role does.
- `install`: the client package.
- `configure`: the mount points and the fstab entries.
Validation runs under `always`, so a bad input fails before any change whatever tags the run selects.
## Example play
```yaml
- name: NFS client
hosts: nfs_clients
roles:
- role: mortis.kamino.nfs_client
vars:
nfs_client_mounts:
- src: nas.example:/export/data
path: /mnt/data
- src: nas.example:/export/media
path: /mnt/media
opts: _netdev,nofail,ro,vers=4.2
```
## Tests
`molecule/default` runs on Ubuntu noble and resolute: a check on a fresh host, the converge, a check on the configured host, an idempotence run, and `verify.yml`. The scenario seeds an fstab line for `/mnt/data` that names another server and a line and a directory for `/mnt/old`, so the run shows that a line is replaced once and that an `absent` entry loses only its line.
`verify.yml` first checks a refusal for each validation on the controller, once, in check mode (a missing or empty `src`, a `src` without an export, a relative path, the root, a trailing slash, options with a space or none, a duplicate path, `mounted` and `remounted`, a host without facts). It then asserts, on each container, the client package, the exact fstab fields, that a new mount point is root's and an existing one keeps its owner and mode, that the removed entry's directory and file are intact, that `/proc/mounts` shows nothing mounted, and that systemd has a mount unit for each new entry and none for the removed one.
What it does not show: that a real share mounts at boot (the server in the scenario does not exist), that `x-systemd.automount` or any option other than the defaults behaves, and Debian trixie.
## Notes
- **Why only the fstab.** `ansible.posix.mount` with `state: mounted` mounts from the play's own process. Where that process runs in a private mount namespace (a hardened sshd unit can), systemd and containers do not see the mount. The role writes the line and reloads systemd, and the share is mounted at the next boot or with `systemctl start <unit>.mount`. New options reach a share that is already mounted only after it is remounted or the host reboots.
- **No owner, group or mode on the mount point.** Once a share is mounted the path is the export root, and a `chown` or `chmod` there changes the permissions on the NFS server. A new directory gets the system defaults, and an existing one is left as it is.
- **A share that is mounted and unreachable.** On a re-run the role looks at each `present` mount point, and a mounted path whose server is gone can block that look. Fix or unmount the share, or leave that entry out of the run, before running the role again.
- **`absent` leaves the share alone.** The entry's line is removed; the share stays mounted until it is unmounted and the mount point is not deleted.
- **Default options.** `_netdev` orders the mount after the network and puts it in `remote-fs.target`; `nofail` keeps an unreachable server from holding up the boot. `x-systemd.automount` changes when a mount appears and can hide an unreachable server until first access, so it is left to the host that wants it. The `docker` role's `docker_stop_at_shutdown` relies on the same `remote-fs.target` ordering.
- `--check` is the supported preview; a play-level `check_mode: true` is not supported. `apt` and the fstab edit both report what would change.
- Idempotent: yes.
+8
View File
@@ -0,0 +1,8 @@
---
# Each entry: src (server:/export) and path (absolute mount point) are required; opts falls back
# to nfs_client_default_opts; state is present (default) or absent.
nfs_client_mounts: []
# _netdev orders the mount after the network and puts it in remote-fs.target; nofail keeps an
# unreachable server from holding up the boot. x-systemd.automount is left to the host that wants it.
nfs_client_default_opts: "_netdev,nofail"
+7
View File
@@ -0,0 +1,7 @@
---
# systemd builds a mount unit from each fstab line only when it reloads, so the reload is what
# makes a changed line known to systemd. It mounts nothing.
- name: Reload systemd for the nfs_client fstab entries
become: true
ansible.builtin.systemd_service:
daemon_reload: true
+57
View File
@@ -0,0 +1,57 @@
---
argument_specs:
main:
short_description: Install the NFS client and manage NFS entries in /etc/fstab
description:
- >-
Asserts a Debian-family host, installs C(nfs-common), creates each mount point of a C(present) entry without
owner, group or mode, writes or removes the entry's line in C(/etc/fstab), and reloads systemd after a change
so that the mount unit is generated now. Nothing is mounted.
- >-
It never mounts or unmounts anything. An C(absent) entry only loses its fstab line: the share stays mounted
until it is unmounted or the host reboots, and the mount point is not removed. Needs gathered facts.
options:
nfs_client_mounts:
type: list
elements: dict
default: []
description:
- >-
The NFS mounts to manage. Each mount point may appear once. With the default (no entries) only the client
package is installed.
options:
src:
type: str
required: true
description:
- The export as C(server:/export), one word without spaces.
path:
type: str
required: true
description:
- >-
The mount point: an absolute path without spaces, not C(/) and without a trailing slash. Created, when
the entry is C(present), with no owner, group or mode.
opts:
type: str
description:
- >-
The fstab options, one comma-separated word without spaces. Falls back to C(nfs_client_default_opts)
when left out or empty. Put the NFS version here, for example C(vers=4.2).
state:
type: str
default: present
choices: [present, absent]
description:
- >-
C(present) writes the fstab line. C(absent) removes it and nothing else. The role has no C(mounted),
C(unmounted) or C(remounted): mounting is left to systemd, so that a mount made from a play running in a
private mount namespace (a hardened sshd unit) cannot go unseen by systemd and by containers.
nfs_client_default_opts:
type: str
default: "_netdev,nofail"
description:
- >-
Options for an entry that sets none. C(_netdev) orders the mount after the network and puts it in
C(remote-fs.target); C(nofail) keeps an unreachable server from holding up the boot.
C(x-systemd.automount) is not in the default.
+18
View File
@@ -0,0 +1,18 @@
---
galaxy_info:
role_name: nfs_client
namespace: mortis
author: Dragonish
license: GPL-3.0-or-later
description: Install the NFS client and manage NFS mount entries in /etc/fstab, without mounting anything.
min_ansible_version: "2.22"
platforms:
- name: Ubuntu
versions:
- noble
- resolute
galaxy_tags:
- nfs
- fstab
- storage
dependencies: []
@@ -0,0 +1,7 @@
---
# The mounts come from molecule.yml.
- name: Converge
hosts: all
gather_facts: true
roles:
- role: mortis.kamino.nfs_client
@@ -0,0 +1,75 @@
---
# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404
# (MOLECULE_IMAGE) and molecule-ubuntu2604 (MOLECULE_IMAGE_2604) images, pinned in
# .gitea/workflows/molecule.yml. Needs the Ubuntu mirrors: the role installs nfs-common. The
# containers run systemd as PID 1 with a writable cgroup, so a daemon-reload builds mount units
# from /etc/fstab; no privileged mode. Nothing is ever mounted: the server below does not exist.
driver:
name: docker
platforms:
- name: ${KAMINO_RUN_ID:-local}-nfs-client-noble
labels:
net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}"
image: ${MOLECULE_IMAGE}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
security_opts:
- apparmor=unconfined
- name: ${KAMINO_RUN_ID:-local}-nfs-client-resolute
labels:
net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}"
image: ${MOLECULE_IMAGE_2604}
pre_build_image: true
pull: true
command: /sbin/init
cgroupns_mode: host
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
tmpfs:
- /run
- /run/lock
security_opts:
- apparmor=unconfined
provisioner:
name: ansible
# One source for every play, so the converge and the plays in verify.yml start from the same
# valid input: a default-options mount, one with its own options, one to remove (prepare.yml
# seeds its line), and /mnt/data, whose seeded line has another server and must be replaced.
inventory:
group_vars:
all:
nfs_client_mounts:
- src: nas.example:/export/data
path: /mnt/data
- src: nas.example:/export/media
path: /mnt/media
opts: _netdev,nofail,ro,vers=4.2
- src: nas.example:/export/old
path: /mnt/old
state: absent
verifier:
name: ansible
scenario:
# molecule's default sequence minus both destroys (scripts/run_molecule_scenarios.sh removes the
# containers as soon as this scenario ends; after a local run, run `molecule destroy` yourself),
# plus a check before the converge (fresh host) and one after it (configured host).
test_sequence:
- dependency
- cleanup
- syntax
- create
- prepare
- check
- converge
- check
- idempotence
- side_effect
- verify
- cleanup
@@ -0,0 +1,43 @@
---
# The state a host has before the role runs: a line for /mnt/data that names another server (the
# role must replace it, once) and a line and a mount point for /mnt/old, the entry the converge
# removes. The file in /mnt/old shows that removing the line leaves the directory alone.
- name: Prepare
hosts: all
gather_facts: false
tasks:
# The image ships without apt lists, and --check does not refresh them, so without this the
# fresh-host check finds no nfs-common to install.
- name: Refresh the apt cache
ansible.builtin.apt:
update_cache: true
- name: Seed the fstab lines
ansible.builtin.lineinfile:
path: /etc/fstab
line: "{{ item }}"
create: true
mode: "0644"
loop:
- old-nas.example:/export/data /mnt/data nfs defaults 0 0
- nas.example:/export/old /mnt/old nfs _netdev,nofail 0 0
- name: Create the mount point that the converge leaves alone
ansible.builtin.file:
path: /mnt/old
state: directory
mode: "0750"
- name: Put a file in it
ansible.builtin.copy:
content: kept
dest: /mnt/old/keep
mode: "0644"
# An existing mount point of a present entry: the role must leave its owner and mode alone.
- name: Create a mount point with an owner and a mode of its own
ansible.builtin.file:
path: /mnt/media
state: directory
owner: daemon
mode: "0710"
@@ -0,0 +1,21 @@
---
# One failing run: includes the role with the inputs the caller sets on the include, and asserts
# that the expected message, not something else, stopped it. Input: nfs_client_test_case (name,
# expect).
- name: "Run the role, case {{ nfs_client_test_case.name }}"
block:
- name: "Include the role, case {{ nfs_client_test_case.name }}"
ansible.builtin.include_role:
name: mortis.kamino.nfs_client
# Only reached when the include returned. The message must not contain the expected
# text, so the rescue below cannot mistake it for the failure under test.
- name: "Fail because the include returned, case {{ nfs_client_test_case.name }}"
ansible.builtin.fail:
msg: The role accepted the input
rescue:
- name: "The expected failure stopped the run, case {{ nfs_client_test_case.name }}"
ansible.builtin.assert:
that: nfs_client_test_case.expect in (ansible_failed_result.msg | default(''))
fail_msg: "Expected '{{ nfs_client_test_case.expect }}', got: {{ ansible_failed_result.msg | default('') }}"
quiet: true
@@ -0,0 +1,247 @@
---
# The refusals below stop in validation, before any task that changes a host, so they need no
# container: they run once, on the controller, in check mode so that a regressed guard cannot
# change it.
#
# Runs first, before any play gathers facts: the role refuses a host it cannot identify as
# Debian-family, before any change.
- name: Refuse a host without facts
hosts: localhost
connection: local
check_mode: true
gather_facts: false
tasks:
- name: Run the role without gathered facts
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_test_case:
name: no-facts
expect: nfs_client supports Debian-family hosts only
# Negative tests: each validation stops the role before any change, with its own message. The
# inputs replace the converge's mounts for one include only.
- name: Refuse invalid input
hosts: localhost
connection: local
check_mode: true
gather_facts: true
tasks:
- name: Refuse a state the role does not have
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data, state: mounted}
nfs_client_test_case:
name: state-mounted
expect: "value of state must be one of: present, absent, got: mounted"
- name: Refuse remounted
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data, state: remounted}
nfs_client_test_case:
name: state-remounted
expect: "value of state must be one of: present, absent, got: remounted"
- name: Refuse an entry without a src
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {path: /mnt/data}
nfs_client_test_case:
name: src-missing
expect: "missing required arguments: src"
- name: Refuse an empty src
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "", path: /mnt/data}
nfs_client_test_case:
name: src-empty
expect: nfs_client_mounts src must be one word of the form server:/export
- name: Refuse a src without an export
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: nas.example, path: /mnt/data}
nfs_client_test_case:
name: src-no-export
expect: nfs_client_mounts src must be one word of the form server:/export
- name: Refuse a src with a space after the export
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/my data", path: /mnt/data}
nfs_client_test_case:
name: src-space
expect: nfs_client_mounts src must be one word of the form server:/export
- name: Refuse a mount point with a space
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: "/mnt/my data"}
nfs_client_test_case:
name: path-space
expect: nfs_client_mounts path must be an absolute path
- name: Refuse a relative mount point
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: mnt/data}
nfs_client_test_case:
name: path-relative
expect: nfs_client_mounts path must be an absolute path
- name: Refuse the root as a mount point
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /}
nfs_client_test_case:
name: path-root
expect: nfs_client_mounts path must be an absolute path
- name: Refuse a trailing slash
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data/}
nfs_client_test_case:
name: path-trailing-slash
expect: nfs_client_mounts path must be an absolute path
- name: Refuse options with a space
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data, opts: "ro, nofail"}
nfs_client_test_case:
name: opts-space
expect: nfs_client_mounts options must be a non-empty comma-separated word
- name: Refuse an entry with no options when the default is empty
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_default_opts: ""
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data}
nfs_client_test_case:
name: opts-empty
expect: nfs_client_mounts options must be a non-empty comma-separated word
- name: Refuse the same mount point twice
ansible.builtin.include_tasks: tasks/failed_run.yml
vars:
nfs_client_mounts:
- {src: "nas.example:/export/data", path: /mnt/data}
- {src: "nas.example:/export/other", path: /mnt/data}
nfs_client_test_case:
name: duplicate-path
expect: nfs_client_mounts lists the same path twice
- name: Verify the host
hosts: all
gather_facts: true
tasks:
- name: Read the installed packages
ansible.builtin.package_facts:
manager: apt
- name: The client package is installed
ansible.builtin.assert:
that:
- "'nfs-common' in ansible_facts.packages"
quiet: true
- name: Read fstab
ansible.builtin.slurp:
src: /etc/fstab
register: nfs_client_test_fstab
# Each line split into its six fields, so the assertions do not depend on the spacing the
# module writes.
- name: Split the fstab lines into fields
ansible.builtin.set_fact:
nfs_client_test_rows: >-
{{ (nfs_client_test_fstab.content | b64decode).splitlines()
| reject('match', '^#')
| map('split')
| reject('equalto', [])
| list }}
# The seeded line for /mnt/data named another server and the default options: the role
# replaces it, so exactly one line is left for the path.
- name: The default-options entry replaced the seeded line
ansible.builtin.assert:
that:
- "['nas.example:/export/data', '/mnt/data', 'nfs', '_netdev,nofail', '0', '0'] in nfs_client_test_rows"
- nfs_client_test_rows | selectattr('1', 'eq', '/mnt/data') | list | length == 1
quiet: true
- name: The entry with its own options keeps them
ansible.builtin.assert:
that:
- "['nas.example:/export/media', '/mnt/media', 'nfs', '_netdev,nofail,ro,vers=4.2', '0', '0'] in nfs_client_test_rows"
quiet: true
- name: The absent entry lost its line
ansible.builtin.assert:
that:
- nfs_client_test_rows | selectattr('1', 'eq', '/mnt/old') | list | length == 0
quiet: true
- name: Stat the mount points
ansible.builtin.stat:
path: "{{ item }}"
loop: [/mnt/data, /mnt/media, /mnt/old, /mnt/old/keep]
register: nfs_client_test_stat
# prepare.yml gave /mnt/media an owner and a mode and /mnt/old a mode of its own. The role
# created /mnt/data (a new directory is root's) and changed neither of the others, and the
# removed entry's directory and the file in it are untouched.
- name: The mount points exist, keep their owner and mode, and the removed entry's directory is intact
ansible.builtin.assert:
that:
- nfs_client_test_stat.results | map(attribute='stat.exists') | min
- nfs_client_test_stat.results[0].stat.isdir
- nfs_client_test_stat.results[0].stat.pw_name == 'root'
- nfs_client_test_stat.results[1].stat.pw_name == 'daemon'
- nfs_client_test_stat.results[1].stat.mode == '0710'
- nfs_client_test_stat.results[2].stat.mode == '0750'
quiet: true
- name: Read what is mounted
ansible.builtin.slurp:
src: /proc/mounts
register: nfs_client_test_mounts
- name: Nothing was mounted
ansible.builtin.assert:
that:
- "'/mnt/data' not in (nfs_client_test_mounts.content | b64decode)"
- "'/mnt/media' not in (nfs_client_test_mounts.content | b64decode)"
quiet: true
# The daemon-reload is what turns an fstab line into a unit; the generator ran again, so the
# new lines have a unit and the removed one has none. systemctl and not the systemd module,
# which fails on a unit that is not loaded, the very state asserted for the removed entry.
- name: Ask systemd about the mount units # noqa: command-instead-of-module
ansible.builtin.command: "systemctl show --property=LoadState --value {{ item }}"
loop: [mnt-data.mount, mnt-media.mount, mnt-old.mount]
register: nfs_client_test_units
changed_when: false
check_mode: false
- name: Systemd knows the new entries and not the removed one
ansible.builtin.assert:
that:
- nfs_client_test_units.results[0].stdout == 'loaded'
- nfs_client_test_units.results[1].stdout == 'loaded'
- nfs_client_test_units.results[2].stdout == 'not-found'
quiet: true
+48
View File
@@ -0,0 +1,48 @@
---
# Validation first, under always, so a bad input fails before any change whatever tags the run
# selects.
- name: Validate the role inputs
ansible.builtin.import_tasks: validate.yml
tags: always
- name: Install the NFS client package
become: true
ansible.builtin.apt:
name: "{{ __nfs_client_package }}"
state: present
update_cache: true
cache_valid_time: 3600
tags: [nfs_client, install]
# No owner, group or mode: once a share is mounted the path is the export root, and a chown or
# chmod there changes the permissions on the NFS server.
- name: Create the mount points # noqa: risky-file-permissions
become: true
ansible.builtin.file:
path: "{{ item.path }}"
state: directory
loop: "{{ __nfs_client_entries | selectattr('state', 'eq', 'present') | list }}"
loop_control:
label: "{{ item.path }}"
tags: [nfs_client, configure]
# present writes the fstab line and mounts nothing. An absent entry only loses its line:
# ansible.posix.mount's own absent would also unmount the share and delete the mount point.
- name: Manage the fstab entries
become: true
ansible.posix.mount:
src: "{{ item.src }}"
path: "{{ item.path }}"
fstype: nfs
opts: "{{ item.opts }}"
dump: "0"
passno: "0"
state: "{{ 'present' if item.state == 'present' else 'absent_from_fstab' }}"
loop: "{{ __nfs_client_entries }}"
loop_control:
label: "{{ item.path }}"
notify: Reload systemd for the nfs_client fstab entries
tags: [nfs_client, configure]
- name: Flush handlers
ansible.builtin.meta: flush_handlers
+73
View File
@@ -0,0 +1,73 @@
---
# Input checks. Imported first in main.yml with tags: always, so a bad input fails before any
# change. The argument spec (types, choices, required keys) runs before this file; the rules
# below are the ones between values. Each assert covers the whole list, not one item per loop
# pass, so the failure message is the assert's own. fstab fields are split on whitespace, so
# "one word" is tested with split rather than a pattern.
# The package and the fstab format are Debian's, and the role reads gathered facts.
- name: Require a Debian-family host
ansible.builtin.assert:
that:
- ansible_facts['os_family'] | default('') == 'Debian'
fail_msg: >-
nfs_client supports Debian-family hosts only (found: {{ ansible_facts['os_family'] | default('no gathered facts') }}).
The role reads gathered facts, so run it in a play that gathers them.
quiet: true
# Fact-computing tasks that the checks below read. A statement block in one template would leave
# whitespace around the result and make it a string instead of a list, so the list is built by
# appending one entry per pass.
- name: Start the resolved entries
ansible.builtin.set_fact:
__nfs_client_entries: []
# Defaults of the suboptions are applied here: the spec's suboption defaults are documentation.
- name: Resolve the entries
ansible.builtin.set_fact:
__nfs_client_entries: >-
{{ __nfs_client_entries + [{
'src': item.src | trim,
'path': item.path,
'opts': (item.opts | default('', true) | trim) or (nfs_client_default_opts | trim),
'state': item.state | default('present', true)
}] }}
loop: "{{ nfs_client_mounts }}"
loop_control:
label: "{{ item.path }}"
- name: Require a server and an export in every src
ansible.builtin.assert:
that:
- __nfs_client_entries | map(attribute='src') | map('split') | map('length') | reject('eq', 1) | list | length == 0
- __nfs_client_entries | map(attribute='src') | reject('search', '^[^ ]+:/') | list | length == 0
fail_msg: >-
nfs_client_mounts src must be one word of the form server:/export, without spaces
(offending: {{ __nfs_client_entries | map(attribute='src') | reject('search', '^[^ ]+:/') | list }}).
quiet: true
- name: Require an absolute mount point that is not the root
ansible.builtin.assert:
that:
- __nfs_client_entries | map(attribute='path') | map('split') | map('length') | reject('eq', 1) | list | length == 0
- __nfs_client_entries | map(attribute='path') | reject('search', '^/[^ ]*[^/ ]$') | list | length == 0
fail_msg: >-
nfs_client_mounts path must be an absolute path without spaces, not the root and without a trailing slash
(offending: {{ __nfs_client_entries | map(attribute='path') | reject('search', '^/[^ ]*[^/ ]$') | list }}).
quiet: true
- name: Require options that fit one fstab field
ansible.builtin.assert:
that:
- __nfs_client_entries | map(attribute='opts') | map('split') | map('length') | reject('eq', 1) | list | length == 0
fail_msg: >-
nfs_client_mounts options must be a non-empty comma-separated word without spaces, from the entry's opts or, when
that is empty, from nfs_client_default_opts.
quiet: true
- name: Require one entry per mount point
ansible.builtin.assert:
that:
- __nfs_client_entries | map(attribute='path') | unique | list | length == __nfs_client_entries | length
fail_msg: nfs_client_mounts lists the same path twice; each mount point may appear once.
quiet: true
+3
View File
@@ -0,0 +1,3 @@
---
# Constant, not an input: the package that carries mount.nfs on Debian and Ubuntu.
__nfs_client_package: nfs-common
@@ -1,6 +1,6 @@
--- ---
# ansible_user is a connection variable: under the docker connection it would # ansible_user is a connection variable: under the docker connection it would
# make `docker exec -u <user>` before the user exists. So the primary user is # run every exec as <user> before the user exists. So the primary user is
# set explicitly instead of through the default ({{ ansible_user }}). # set explicitly instead of through the default ({{ ansible_user }}).
# bootstrap.yml: wait_for_connection succeeds over the docker connection, so the # bootstrap.yml: wait_for_connection succeeds over the docker connection, so the
# root fallback is never taken. # root fallback is never taken.
+35 -3
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# The Molecule workflow's "Run the scenarios" step: `molecule test` for each scenario directory on # The Molecule workflow's "Run the scenarios" step: `molecule test` for each scenario directory on
# stdin, MOLECULE_LANES (default 4) at a time, each with its own log and ANSIBLE_HOME under # stdin, MOLECULE_LANES (default 4, also when empty) at a time, longest first, each with its own
# <work-dir>/<n>/ (no collection is installed there: .config/molecule/config.yml sets prerun false). # log and ANSIBLE_HOME under <work-dir>/<n>/ (no collection is installed there:
# .config/molecule/config.yml sets prerun false).
# Exit 1 on a failure. # Exit 1 on a failure.
# #
# scripts/run_molecule_scenarios.sh <work-dir> < scenario-dirs # scripts/run_molecule_scenarios.sh <work-dir> < scenario-dirs
@@ -77,6 +78,37 @@ while IFS= read -r dir; do
done done
mkdir -p "$work" mkdir -p "$work"
# Seconds each scenario took in the last full run, so the longest start first and none started
# late sets the end of the run. Keyed by scenario directory, not label: refresh from a full run's
# `finished <label>: exit 0 after S s` lines, each label mapped back to its directory. A scenario
# missing here is assumed long and starts first.
declare -A last_seconds=(
[roles/system_baseline/molecule/default]=1127
[roles/ufw/molecule/default]=907
[roles/traefik/molecule/default]=886
[roles/gitea_runner/molecule/default]=762
[roles/cloudflared/molecule/default]=673
[roles/docker/molecule/default]=612
[roles/tailscale/molecule/default]=509
[roles/fail2ban/molecule/default]=337
[roles/systemd_hardening/molecule/default]=335
[roles/gitea/molecule/default]=301
[roles/user_management/molecule/default]=270
[roles/_binary_update/molecule/default]=248
[roles/pihole/molecule/default]=228
[roles/sshd/molecule/default]=163
[roles/pve_lxc/molecule/default]=157
[roles/network_interfaces/molecule/default]=129
[roles/_binary_update/molecule/check_mode]=81
[extensions/molecule/image-smoke]=47
[extensions/molecule/image-smoke-2604]=46
)
# The indices of dirs in start order; ties keep the selection order (a stable sort).
mapfile -t start_order < <(
for n in "${!dirs[@]}"; do printf '%s %s\n' "${last_seconds[${dirs[$n]}]:-999999}" "$n"; done |
sort -s -k1,1nr | cut -d' ' -f2
)
# A cancelled job must not leave lanes behind that recreate containers after the next run's # A cancelled job must not leave lanes behind that recreate containers after the next run's
# cleanup. A signal to this script stops each lane's tree so it cannot fork, then terminates it, # cleanup. A signal to this script stops each lane's tree so it cannot fork, then terminates it,
# with the whole group of any descendant that leads one: ansible's workers detach into their own. # with the whole group of any descendant that leads one: ansible's workers detach into their own.
@@ -110,7 +142,7 @@ trap 'stop_lanes 143' TERM
trap 'stop_lanes 130' INT trap 'stop_lanes 130' INT
trap 'stop_lanes 129' HUP trap 'stop_lanes 129' HUP
for n in "${!dirs[@]}"; do for n in "${start_order[@]}"; do
while [ "$(jobs -rp | wc -l)" -ge "$lanes" ]; do wait -n || true; done while [ "$(jobs -rp | wc -l)" -ge "$lanes" ]; do wait -n || true; done
run_one "$n" "${dirs[$n]}" </dev/null & run_one "$n" "${dirs[$n]}" </dev/null &
done done
@@ -42,7 +42,9 @@ exit 0
# The scenario runner: records its arguments, paths and stdin. # The scenario runner: records its arguments, paths and stdin.
RUNNER_STUB = """#!/usr/bin/env bash RUNNER_STUB = """#!/usr/bin/env bash
echo "runner args=$* path=$PATH acp=$ANSIBLE_COLLECTIONS_PATH inject=${ANSIBLE_INJECT_FACT_VARS-unset} stdin=[$(cat | tr '\\n' ' ')]" >> "$STUB_LOG" echo "runner args=$* path=$PATH acp=$ANSIBLE_COLLECTIONS_PATH" \\
"inject=${ANSIBLE_INJECT_FACT_VARS-unset} lanes=${MOLECULE_LANES-unset}" \\
"stdin=[$(cat | tr '\\n' ' ')]" >> "$STUB_LOG"
""" """
@@ -161,6 +163,12 @@ class RunMoleculeInCiImageTest(unittest.TestCase):
runner, runner,
) )
def test_the_lane_count_reaches_the_scenario_runner(self):
result = self.run_script(MOLECULE_LANES="3")
self.assertEqual(result.returncode, 0, result.stderr)
(runner,) = self.calls("runner")
self.assertIn(" lanes=3 ", runner)
def test_the_load_check_sees_the_selection_and_the_final_path(self): def test_the_load_check_sees_the_selection_and_the_final_path(self):
selection = "roles/alpha/molecule/default\nextensions/molecule/image-smoke\n" selection = "roles/alpha/molecule/default\nextensions/molecule/image-smoke\n"
result = self.run_script(selection, STUB_FAIL_sha256sum="1") result = self.run_script(selection, STUB_FAIL_sha256sum="1")
@@ -283,6 +283,46 @@ class RunMoleculeScenariosTest(unittest.TestCase):
self.assertEqual(proc.returncode, 1) self.assertEqual(proc.returncode, 1)
self.assertIn("::error::ran 1 of 2 selected scenarios", proc.stdout) self.assertIn("::error::ran 1 of 2 selected scenarios", proc.stdout)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_the_longest_scenarios_start_first(self):
# an unlisted scenario counts as longest; the groups keep the selection order
seconds = listed_seconds()
roles = [d for d in seconds if d.startswith("roles/")]
shortest, longest = min(roles, key=seconds.get), max(roles, key=seconds.get)
for scenario in (shortest, longest):
d = self.root / scenario
d.mkdir(parents=True)
name = f"{RUN_ID}-{scenario.replace('/', '-')}"
platforms = [{"name": name, "image": "${MOLECULE_IMAGE}"}]
(d / "molecule.yml").write_text(yaml.safe_dump({"platforms": platforms}))
smoke = "extensions/molecule/image-smoke"
order = [smoke, shortest, "roles/alpha/molecule/default", longest]
listed = sorted((smoke, shortest, longest), key=seconds.get, reverse=True)
proc = self.run_script(order, MOLECULE_LANES="1")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
spans = self.events()
self.assertEqual(
sorted(spans, key=lambda label: spans[label][0]),
[label(d) for d in ["roles/alpha/molecule/default", *listed]],
)
groups = re.findall(
r"^::group::molecule test: (\S+) ", proc.stdout, re.MULTILINE
)
self.assertEqual(groups, [label(d) for d in order])
def test_the_duration_list_names_existing_scenarios(self):
# a renamed scenario would otherwise drop out of the list unnoticed
listed = listed_seconds()
self.assertTrue(listed)
for scenario in listed:
self.assertTrue((REPO / scenario / "molecule.yml").is_file(), scenario)
@unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE)
def test_empty_lanes_are_accepted(self):
# the workflow passes an empty value outside a manual dispatch
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES="")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
def test_lanes_must_be_a_positive_integer(self): def test_lanes_must_be_a_positive_integer(self):
for lanes in ("0", "-1", "two", "04"): for lanes in ("0", "-1", "two", "04"):
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES=lanes) proc = self.run_script(list(PLATFORMS), MOLECULE_LANES=lanes)
@@ -349,6 +389,20 @@ class RunMoleculeScenariosTest(unittest.TestCase):
self.assertEqual(self.log.read_text(), "") self.assertEqual(self.log.read_text(), "")
def listed_seconds():
"""{scenario directory: seconds} from the run script's duration list."""
pairs = re.findall(r"^ \[([^]]+)\]=(\d+)$", SCRIPT.read_text(), re.MULTILINE)
return {d: int(s) for d, s in pairs}
def label(scenario):
"""The run script's label of a scenario directory, as its log groups print it."""
if scenario.startswith("extensions/"):
return scenario.rsplit("/", 1)[1]
parts = scenario.split("/")
return f"{parts[1]}/{parts[3]}"
def alive(pid): def alive(pid):
"""Whether pid is a running process, not gone or a zombie.""" """Whether pid is a running process, not gone or a zombie."""
try: try:
@@ -416,6 +470,20 @@ class ScenarioPlatformsTest(unittest.TestCase):
) )
class LanesInputTest(unittest.TestCase):
"""A manual dispatch can set the lane count of the run script inside the run container."""
def test_the_dispatch_input_reaches_the_run_container(self):
workflow = yaml.safe_load(WORKFLOW.read_text())
# yaml reads the `on:` key as True
lanes = workflow[True]["workflow_dispatch"]["inputs"]["lanes"]
self.assertEqual((lanes["type"], lanes["default"]), ("string", ""))
steps = workflow["jobs"]["molecule"]["steps"]
step = next(s for s in steps if s.get("name") == "Run the scenarios")
self.assertEqual(step["env"]["MOLECULE_LANES"], "${{ inputs.lanes }}")
self.assertRegex(step["run"], r"docker run [^<]*-e MOLECULE_LANES\b")
class ScenarioSequenceTest(unittest.TestCase): class ScenarioSequenceTest(unittest.TestCase):
"""A role scenario previews the fresh host and the configured host with molecule's check step.""" """A role scenario previews the fresh host and the configured host with molecule's check step."""