From 26b6e37a095985d761da6c60a11b8a7d319e7aaa Mon Sep 17 00:00:00 2001 From: Dragonish Date: Thu, 26 Nov 2026 21:19:57 +0000 Subject: [PATCH 01/26] fix: read facts through ansible_facts and run Molecule with fact injection off ansible-core deprecates injecting facts as top-level variables (removal is scheduled for 2.24, see #364). Three roles still read a bare fact: system_baseline (reboot check, ansible_os_family), docker (APT source line, ansible_distribution_release) and gitea_runner (re-registration backup name, ansible_date_time). With inject_facts_as_vars set to false the system_baseline reboot check failed with "'ansible_os_family' is undefined". They now read ansible_facts[...]; the argument specs and READMEs that name the facts follow. run_molecule_in_ci_image.sh exports ANSIBLE_INJECT_FACT_VARS=False, so a role that reads an injected fact fails its scenario, and a script test keeps the export in place. Refs #364 Assisted-by: Claude Code:claude-sonnet-5-5 --- changelogs/fragments/364-ansible-facts.yml | 15 +++++++++++++++ roles/docker/README.md | 4 ++-- roles/docker/meta/argument_specs.yml | 4 ++-- roles/docker/tasks/install.yml | 2 +- roles/gitea_runner/README.md | 2 +- roles/gitea_runner/meta/argument_specs.yml | 2 +- roles/gitea_runner/tasks/main.yml | 2 +- roles/system_baseline/README.md | 2 +- roles/system_baseline/meta/argument_specs.yml | 4 ++-- roles/system_baseline/tasks/reboot.yml | 2 +- scripts/run_molecule_in_ci_image.sh | 3 +++ tests/scripts/test_run_molecule_in_ci_image.py | 12 +++++++++++- 12 files changed, 41 insertions(+), 13 deletions(-) create mode 100644 changelogs/fragments/364-ansible-facts.yml diff --git a/changelogs/fragments/364-ansible-facts.yml b/changelogs/fragments/364-ansible-facts.yml new file mode 100644 index 0000000..30b737a --- /dev/null +++ b/changelogs/fragments/364-ansible-facts.yml @@ -0,0 +1,15 @@ +--- +bugfixes: + - >- + docker - Read the distribution release through ``ansible_facts['distribution_release']`` for the APT + source line, so the role works with ``inject_facts_as_vars`` set to false and in the ansible-core + release that stops injecting facts as variables. The source line is unchanged. + - >- + gitea_runner - Read the timestamp of the forced re-registration backup through + ``ansible_facts['date_time']``, so the role works with ``inject_facts_as_vars`` set to false and in + the ansible-core release that stops injecting facts as variables. The backup name is unchanged. + - >- + system_baseline - Read the OS family through ``ansible_facts['os_family']`` in the reboot check, so + the role (and its ``reboot`` entry point) works with ``inject_facts_as_vars`` set to false and in + the ansible-core release that stops injecting facts as variables. Before, the task failed with + ``'ansible_os_family' is undefined`` there. diff --git a/roles/docker/README.md b/roles/docker/README.md index 5c75a89..eee758c 100644 --- a/roles/docker/README.md +++ b/roles/docker/README.md @@ -4,7 +4,7 @@ Installs Docker Engine from the upstream Docker APT repository, optionally updat ## Supported platforms -Ubuntu 24.04 (noble) and 26.04 (resolute), the platforms the molecule scenario runs on. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_distribution_release`. The apt architecture is derived from the host (`x86_64` gives `amd64`, `aarch64` gives `arm64`); any other architecture fails the play until `docker_apt_arch` is set. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested. +Ubuntu 24.04 (noble) and 26.04 (resolute), the platforms the molecule scenario runs on. The key and repository URLs point at `download.docker.com/linux/ubuntu`, and the source line uses `ansible_facts['distribution_release']`. The apt architecture is derived from the host (`x86_64` gives `amd64`, `aarch64` gives `arm64`); any other architecture fails the play until `docker_apt_arch` is set. A limited molecule scenario covers the role's own logic (see [Tests](#tests)); the real Docker Engine is not tested. The role targets Ubuntu hosts only: it installs from Docker's Ubuntu repository, so it does not cover Debian trixie (Proxmox hosts). @@ -91,7 +91,7 @@ With any of `docker_daemon_options`, `docker_live_restore`, `docker_log_driver`, 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 source line has the architecture, the `signed-by` keyring and `ansible_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`. - `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. diff --git a/roles/docker/meta/argument_specs.yml b/roles/docker/meta/argument_specs.yml index 9ec341b..822b9e0 100644 --- a/roles/docker/meta/argument_specs.yml +++ b/roles/docker/meta/argument_specs.yml @@ -6,7 +6,7 @@ argument_specs: - >- Installs Docker Engine from the upstream APT repository, or removes it when C(docker_remove) is true. Optionally updates the packages to the current candidate versions, then adds C(docker_users) to C(docker_group). - - Needs gathered facts, because the APT source uses C(ansible_distribution_release). + - Needs gathered facts, because the APT source uses C(ansible_facts['distribution_release']). options: docker_remove: type: bool @@ -53,7 +53,7 @@ argument_specs: type: str default: https://download.docker.com/linux/ubuntu description: - - Base URL of the repository. The source line uses C(ansible_distribution_release) and the C(stable) component. + - Base URL of the repository. The source line uses C(ansible_facts['distribution_release']) and the C(stable) component. docker_apt_arch: type: str default: "" diff --git a/roles/docker/tasks/install.yml b/roles/docker/tasks/install.yml index 31f6543..710fb2e 100644 --- a/roles/docker/tasks/install.yml +++ b/roles/docker/tasks/install.yml @@ -30,7 +30,7 @@ ansible.builtin.copy: dest: "{{ docker_apt_list_path }}" content: | - deb [arch={{ __docker_apt_arch }} signed-by={{ docker_keyring_path }}] {{ docker_repo_base_url }} {{ ansible_distribution_release }} stable + deb [arch={{ __docker_apt_arch }} signed-by={{ docker_keyring_path }}] {{ docker_repo_base_url }} {{ ansible_facts['distribution_release'] }} stable mode: "0644" register: __docker_apt_source tags: [docker, install] diff --git a/roles/gitea_runner/README.md b/roles/gitea_runner/README.md index 6396e88..875cca9 100644 --- a/roles/gitea_runner/README.md +++ b/roles/gitea_runner/README.md @@ -18,7 +18,7 @@ The role targets Ubuntu hosts that run CI jobs, not Proxmox nodes, so it does no - The registration token is generated on the fly, held in a `no_log` fact and passed to `gitea-runner register` through the `GITEA_RUNNER_REGISTRATION_TOKEN` environment variable, not argv. It is never written to a file by the role. - The role creates `gitea_runner_group` and `gitea_runner_user` when they are missing; an existing account (for example the SSH login user) is reused. - Docker is installed by this role (`tasks/docker.yml`) on first install, not by `mortis.kamino.docker`. -- Fact gathering must be on for `gitea_runner_force_register`: the backup name uses `ansible_date_time`. +- Fact gathering must be on for `gitea_runner_force_register`: the backup name uses `ansible_facts['date_time']`. - Updates: the update path stages the verified binary and hands the swap to `mortis.kamino._binary_update`, an internal role of this Collection. - `gitea_runner_version` is asserted at role start to be a plain `X.Y.Z` release number, with no leading `v`. Pin it in inventory to move the runner independently of Collection releases; the role default changes only with a release. - The executor and job image of a job come from its label's suffix (`:host` or `docker://`); a label with no suffix runs its jobs on the host. `config.yaml` has no keys for them. diff --git a/roles/gitea_runner/meta/argument_specs.yml b/roles/gitea_runner/meta/argument_specs.yml index 0eab5d1..c774d7f 100644 --- a/roles/gitea_runner/meta/argument_specs.yml +++ b/roles/gitea_runner/meta/argument_specs.yml @@ -19,7 +19,7 @@ argument_specs: C(gitea_runner_token_host), C(gitea_runner_instance_url) and C(gitea_runner_name) have empty role defaults and are asserted only when registration runs, so a run that never registers is not blocked. - >- - Reads gathered facts (C(ansible_date_time), for the forced re-registration backup name) and + Reads gathered facts (C(ansible_facts['date_time']), for the forced re-registration backup name) and C(ansible_check_mode). options: gitea_runner_remove: diff --git a/roles/gitea_runner/tasks/main.yml b/roles/gitea_runner/tasks/main.yml index 8f5ebe2..e0c3b50 100644 --- a/roles/gitea_runner/tasks/main.yml +++ b/roles/gitea_runner/tasks/main.yml @@ -71,7 +71,7 @@ become: true ansible.builtin.copy: src: "{{ gitea_runner_work_dir }}/.runner" - dest: "{{ gitea_runner_work_dir }}/.runner.bak.{{ ansible_date_time.iso8601_basic_short }}" + dest: "{{ gitea_runner_work_dir }}/.runner.bak.{{ ansible_facts['date_time']['iso8601_basic_short'] }}" remote_src: true owner: "{{ gitea_runner_state.stat.pw_name }}" group: "{{ gitea_runner_state.stat.gr_name }}" diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index 480678a..84b6712 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -12,7 +12,7 @@ The role targets Ubuntu guests (the `ubuntu_lxc` and `ubuntu_vm` profiles) and P ## Requirements and run order -- Facts must be gathered (`gather_facts: true`); `reboot.yml` reads `ansible_os_family`. +- Facts must be gathered (`gather_facts: true`); `reboot.yml` reads `ansible_facts['os_family']`. - `system_baseline_system_type` is required and has no default (the role does not read a global such as `system_type`; map it in the inventory). Valid values: `ubuntu_lxc`, `ubuntu_vm` or `pve`. - Use it by its fully qualified name, `mortis.kamino.system_baseline`. - Collections: `community.general` (locale, timezone) and `ansible.posix` (sysctl, mount). diff --git a/roles/system_baseline/meta/argument_specs.yml b/roles/system_baseline/meta/argument_specs.yml index 6f36c6b..48d8ff0 100644 --- a/roles/system_baseline/meta/argument_specs.yml +++ b/roles/system_baseline/meta/argument_specs.yml @@ -7,7 +7,7 @@ argument_specs: Validates C(system_baseline_system_type) and, when C(system_baseline_tmux_autostart) is true, the tmux session name and windows, then runs the update (unless C(system_baseline_update) is false), packages, unattended-upgrades, locale, timezone, journald, apt-daily timeout (when set), sysctl, tmpfs, tmux and reboot task files, in that order. - - Needs gathered facts, because the reboot check reads C(ansible_os_family). + - Needs gathered facts, because the reboot check reads C(ansible_facts['os_family']). - >- The resolved inputs C(system_baseline_profile), C(system_baseline_essential_packages), C(system_baseline_remove_packages), C(system_baseline_apt_periodic_settings), C(system_baseline_apt_upgrade), @@ -187,7 +187,7 @@ argument_specs: never reboots, so a caller can read C(system_baseline_reboot_required) (bool) and reboot on its own terms, for example after draining a node. The fact name and this behaviour are part of the role's interface. - On a non-Debian host the fact is not set; read it with C(default(false)). - - Reads C(ansible_os_family), so facts must be gathered. + - Reads C(ansible_facts['os_family']), so facts must be gathered. options: system_baseline_reboot_if_required: type: bool diff --git a/roles/system_baseline/tasks/reboot.yml b/roles/system_baseline/tasks/reboot.yml index 900b109..0a26d55 100644 --- a/roles/system_baseline/tasks/reboot.yml +++ b/roles/system_baseline/tasks/reboot.yml @@ -4,7 +4,7 @@ ansible.builtin.import_tasks: validate_reboot.yml - name: Check if reboot required (Debian) - when: ansible_os_family == "Debian" + when: ansible_facts['os_family'] == "Debian" block: - name: Check if reboot is required (Debian) ansible.builtin.stat: diff --git a/scripts/run_molecule_in_ci_image.sh b/scripts/run_molecule_in_ci_image.sh index b0e9f4a..b471a24 100755 --- a/scripts/run_molecule_in_ci_image.sh +++ b/scripts/run_molecule_in_ci_image.sh @@ -32,5 +32,8 @@ molecule --version # The collection under test first; molecule also installs it into each scenario's ANSIBLE_HOME, # which the run script keeps in the job tree. export ANSIBLE_COLLECTIONS_PATH="$AC_ROOT:${extra_collections}/opt/collections" +# Facts are not injected as variables (deprecated in ansible-core 2.22, removal scheduled for 2.24, see #364), so a +# role that reads a bare `ansible_` fails its scenario here instead of in a consumer's inventory. +export ANSIBLE_INJECT_FACT_VARS=False python3 -I scripts/check_scenarios_load_checkout.py <<< "$selected" exec scripts/run_molecule_scenarios.sh "$AC_ROOT/molecule-runs" <<< "$selected" diff --git a/tests/scripts/test_run_molecule_in_ci_image.py b/tests/scripts/test_run_molecule_in_ci_image.py index ac09cc8..28cc1db 100644 --- a/tests/scripts/test_run_molecule_in_ci_image.py +++ b/tests/scripts/test_run_molecule_in_ci_image.py @@ -42,7 +42,7 @@ exit 0 # The scenario runner: records its arguments, paths and stdin. RUNNER_STUB = """#!/usr/bin/env bash -echo "runner args=$* path=$PATH acp=$ANSIBLE_COLLECTIONS_PATH stdin=[$(cat | tr '\\n' ' ')]" >> "$STUB_LOG" +echo "runner args=$* path=$PATH acp=$ANSIBLE_COLLECTIONS_PATH inject=${ANSIBLE_INJECT_FACT_VARS-unset} stdin=[$(cat | tr '\\n' ' ')]" >> "$STUB_LOG" """ @@ -112,6 +112,16 @@ class RunMoleculeInCiImageTest(unittest.TestCase): self.assertIn(f"acp={self.ac_root}:/opt/collections ", runner) self.assertIn(f"args={self.ac_root}/molecule-runs ", runner) + def test_scenarios_run_with_fact_injection_off(self): + # A role that reads a bare ansible_ must fail its scenario here (#364), whichever way the pins went. + for fail in ("", "1"): + with self.subTest(pins_differ=bool(fail)): + self.log.write_text("") + result = self.run_script(STUB_FAIL_sha256sum=fail) + self.assertEqual(result.returncode, 0, result.stderr) + (runner,) = self.calls("runner") + self.assertIn(" inject=False ", runner) + def test_changed_pins_are_installed_and_put_first(self): result = self.run_script(STUB_FAIL_sha256sum="1") self.assertEqual(result.returncode, 0, result.stderr) From a659e83e6b6ee5ea059fe590f3892678765b8917 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Thu, 26 Nov 2026 21:56:10 +0000 Subject: [PATCH 02/26] chore(release): 3.1.0 Minor release: adds the tailscale role, and fixes six roles that failed under --check on a host where they were not installed yet. Assisted-by: Claude Code:claude-opus-5-5 --- CHANGELOG.rst | 18 ++++++++++++++++ README.md | 4 ++-- changelogs/.plugin-cache.yaml | 6 +++++- changelogs/changelog.yaml | 28 +++++++++++++++++++++++++ changelogs/fragments/134-check-mode.yml | 17 --------------- changelogs/fragments/tailscale-role.yml | 9 -------- galaxy.yml | 2 +- 7 files changed, 54 insertions(+), 30 deletions(-) delete mode 100644 changelogs/fragments/134-check-mode.yml delete mode 100644 changelogs/fragments/tailscale-role.yml diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5e714a7..c20337f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -4,6 +4,24 @@ mortis.kamino Release Notes .. contents:: Topics +v3.1.0 +====== + +Minor Changes +------------- + +- tailscale - New role. Installs Tailscale from the upstream APT repository with the keyring pinned by sha256, sets ``--tun=userspace-networking`` in the ``tailscaled`` flags when ``tailscale_userspace_networking`` is true, enables ``tailscaled`` and, with ``tailscale_up`` (default ``true``), runs ``tailscale up`` with ``tailscale_auth_key`` while the node is not Running; it can also update to the APT candidate version and remove or purge. Declares Ubuntu noble and resolute; the molecule scenario installs the real package but does not join a tailnet. + +Bugfixes +-------- + +- cloudflared - Do not fail under ``--check`` on a host where the cloudflared account or systemd unit does not exist yet. +- docker - Do not fail under ``--check`` on a host where the Docker repository and packages are not installed yet. +- gitea - Do not fail under ``--check`` on a host where Gitea is not installed yet. +- gitea_runner - Do not fail under ``--check`` on a host where the runner account, Docker or the systemd unit does not exist yet. +- traefik - Do not fail under ``--check`` on a host where Traefik is not installed yet. +- user_management - Do not fail under ``--check`` when a managed user does not exist yet. + v3.0.0 ====== diff --git a/README.md b/README.md index ee00e4d..b2f970d 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ An Ansible Collection of reusable, hardened roles for a self-hosted home lab: `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). -Status: roles arrive in waves. Release 3.0.0 holds the `cloudflared`, `docker`, `fail2ban`, `gitea`, `gitea_runner`, `network_interfaces`, `pihole`, `pve_lxc`, `sshd`, `system_baseline`, `systemd_hardening`, `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.1.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). ## Consuming @@ -17,7 +17,7 @@ name (FQCN) only, `mortis.kamino.`: collections: - name: https://git.rkdr.net/mortis/kamino.git type: git - version: v3.0.0 + version: v3.1.0 ``` Its dependencies (`community.general`, `ansible.posix`, `community.proxmox`) are declared in `galaxy.yml`, so diff --git a/changelogs/.plugin-cache.yaml b/changelogs/.plugin-cache.yaml index 8b38374..8d3c40a 100644 --- a/changelogs/.plugin-cache.yaml +++ b/changelogs/.plugin-cache.yaml @@ -51,6 +51,10 @@ objects: description: Harden systemd for a system type name: systemd_hardening version_added: null + tailscale: + description: Install Tailscale and bring the node up + name: tailscale + version_added: null traefik: description: Install, configure, update or remove Traefik as a systemd binary name: traefik @@ -81,4 +85,4 @@ plugins: strategy: {} test: {} vars: {} -version: 3.0.0 +version: 3.1.0 diff --git a/changelogs/changelog.yaml b/changelogs/changelog.yaml index 0b22a3c..8e11d64 100644 --- a/changelogs/changelog.yaml +++ b/changelogs/changelog.yaml @@ -446,3 +446,31 @@ releases: - 133-drop-jammy-and-ubuntu-all.yml - 133-ubuntu-2604.yml release_date: '2026-11-26' + 3.1.0: + changes: + bugfixes: + - cloudflared - Do not fail under ``--check`` on a host where the cloudflared + account or systemd unit does not exist yet. + - docker - Do not fail under ``--check`` on a host where the Docker repository + and packages are not installed yet. + - gitea - Do not fail under ``--check`` on a host where Gitea is not installed + yet. + - gitea_runner - Do not fail under ``--check`` on a host where the runner account, + Docker or the systemd unit does not exist yet. + - traefik - Do not fail under ``--check`` on a host where Traefik is not installed + yet. + - user_management - Do not fail under ``--check`` when a managed user does not + exist yet. + minor_changes: + - tailscale - New role. Installs Tailscale from the upstream APT repository + with the keyring pinned by sha256, sets ``--tun=userspace-networking`` in + the ``tailscaled`` flags when ``tailscale_userspace_networking`` is true, + enables ``tailscaled`` and, with ``tailscale_up`` (default ``true``), runs + ``tailscale up`` with ``tailscale_auth_key`` while the node is not Running; + it can also update to the APT candidate version and remove or purge. Declares + Ubuntu noble and resolute; the molecule scenario installs the real package + but does not join a tailnet. + fragments: + - 134-check-mode.yml + - tailscale-role.yml + release_date: '2026-11-26' diff --git a/changelogs/fragments/134-check-mode.yml b/changelogs/fragments/134-check-mode.yml deleted file mode 100644 index b10398a..0000000 --- a/changelogs/fragments/134-check-mode.yml +++ /dev/null @@ -1,17 +0,0 @@ ---- -bugfixes: - - >- - cloudflared - Do not fail under ``--check`` on a host where the cloudflared account or systemd - unit does not exist yet. - - >- - docker - Do not fail under ``--check`` on a host where the Docker repository and packages are - not installed yet. - - >- - gitea - Do not fail under ``--check`` on a host where Gitea is not installed yet. - - >- - gitea_runner - Do not fail under ``--check`` on a host where the runner account, Docker or the - systemd unit does not exist yet. - - >- - traefik - Do not fail under ``--check`` on a host where Traefik is not installed yet. - - >- - user_management - Do not fail under ``--check`` when a managed user does not exist yet. diff --git a/changelogs/fragments/tailscale-role.yml b/changelogs/fragments/tailscale-role.yml deleted file mode 100644 index 64f1bed..0000000 --- a/changelogs/fragments/tailscale-role.yml +++ /dev/null @@ -1,9 +0,0 @@ ---- -minor_changes: - - >- - tailscale - New role. Installs Tailscale from the upstream APT repository with the keyring pinned by sha256, - sets ``--tun=userspace-networking`` in the ``tailscaled`` flags when ``tailscale_userspace_networking`` is true, - enables ``tailscaled`` and, with ``tailscale_up`` (default ``true``), runs ``tailscale up`` with - ``tailscale_auth_key`` while the node is not Running; it can also update to the APT candidate version and remove - or purge. Declares Ubuntu noble and resolute; the molecule scenario installs the real package but does not join a - tailnet. diff --git a/galaxy.yml b/galaxy.yml index fd5c00c..f930b4d 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -1,7 +1,7 @@ --- namespace: mortis name: kamino -version: 3.0.0 +version: 3.1.0 readme: README.md authors: - Defame1297 From f7fde63f7d59233a0f0818ef54a03655100db62b Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Thu, 26 Nov 2026 22:17:42 +0000 Subject: [PATCH 03/26] ci: run the Lint and Build fast path without network When the pins match the ci image every tool is baked in, so a runtime download is a bake-in defect; failing the job makes it visible. Assisted-by: Claude Code --- .gitea/workflows/AGENTS.md | 5 +++++ .gitea/workflows/build.yml | 13 ++++++++----- .gitea/workflows/lint.yml | 14 +++++++++----- docs/images/ci.md | 3 ++- images/AGENTS.md | 5 +++-- 5 files changed, 27 insertions(+), 13 deletions(-) diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index f5afa9c..cc34b0b 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -57,6 +57,11 @@ issue. `.pre-commit-config.yaml` takes the slow path, which installs the pinned tools and collections. *Why:* a pull request is tested on its own pins, and an unchanged one starts in seconds. *Held:* control: the "Check the baked tooling against the pins" step. +- **On the fast path the tool steps run in a network namespace without network** (`unshare -rn` + through `$OFFLINE`), except "Test the repository scripts", whose fake registry needs loopback; + the slow path keeps network. *Why:* a runtime download is a bake-in defect and must fail the + job, not silently slow it. *Held:* control: the `$OFFLINE` prefix set by the "Check the baked + tooling against the pins" step. - **Triggers:** both run on pull requests to `main` and on manual dispatch; Build also runs on `v*` tags, where it checks the tag against `galaxy.yml`. *Why:* the tag is what consumers install. *Held:* review. diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 16216f4..a71904c 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -60,6 +60,9 @@ jobs: run: | if sha256sum --quiet -c /opt/ci-pins.sha256; then echo "The pin files match the ci image; using the baked tools." + # -r adds a user namespace: a job container lacks CAP_SYS_ADMIN for a plain unshare -n. + echo "OFFLINE=unshare -rn --" >> "$GITHUB_ENV" + echo "::notice::The tool steps run without network; a download fails the job (bake it into images/ci)." else echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \ "extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \ @@ -79,7 +82,7 @@ jobs: echo "::error::$TAG is a lightweight tag; releases must be annotated (git tag -a)" exit 1 fi - version="$(python3 -c 'import sys, yaml; print(yaml.safe_load(open("galaxy.yml"))["version"])')" + version="$($OFFLINE python3 -c 'import sys, yaml; print(yaml.safe_load(open("galaxy.yml"))["version"])')" if [ "$TAG" != "v$version" ]; then echo "::error::tag $TAG does not match galaxy.yml version $version (expected v$version)" exit 1 @@ -106,7 +109,7 @@ jobs: run: | export PATH="/opt/venv/bin:$PATH" mkdir -p /tmp/dist - ansible-galaxy collection build --force --output-path /tmp/dist . + $OFFLINE ansible-galaxy collection build --force --output-path /tmp/dist . ls -l /tmp/dist sha256sum /tmp/dist/*.tar.gz @@ -119,7 +122,7 @@ jobs: echo "::error::expected exactly one tarball in /tmp/dist, found $# match(es): $*" exit 1 fi - python3 scripts/check_tarball.py "$1" + $OFFLINE python3 scripts/check_tarball.py "$1" # galaxy-importer without ansible-test and without Docker. The importer reads its # configuration from this file. @@ -138,7 +141,7 @@ jobs: exit 1 fi GALAXY_IMPORTER_CONFIG=/tmp/galaxy-importer.cfg \ - python3 -m galaxy_importer.main "$1" + $OFFLINE python3 -m galaxy_importer.main "$1" # Sanity tests need the collection at ansible_collections//. - name: Run ansible-test sanity @@ -159,4 +162,4 @@ jobs: { cat tests/sanity/ignore-common.txt; if [ -f "$ignore" ]; then cat "$ignore"; fi; } > /tmp/ignore.new mv /tmp/ignore.new "$ignore" echo "Sanity ignore list for ansible-core ${core}: $(wc -l < "$ignore") lines" - ansible-test sanity --requirements --color no + $OFFLINE ansible-test sanity --requirements --color no diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 2a8515e..a6f65a2 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -59,6 +59,9 @@ jobs: run: | if sha256sum --quiet -c /opt/ci-pins.sha256; then echo "The pin files match the ci image; using the baked tools." + # -r adds a user namespace: a job container lacks CAP_SYS_ADMIN for a plain unshare -n. + echo "OFFLINE=unshare -rn --" >> "$GITHUB_ENV" + echo "::notice::The tool steps run without network; a download fails the job (bake it into images/ci)." else echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \ "extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \ @@ -71,7 +74,7 @@ jobs: - name: Run pre-commit on all files run: | export PATH="/opt/venv/bin:$PATH" - pre-commit run --all-files --show-diff-on-failure + $OFFLINE pre-commit run --all-files --show-diff-on-failure # Image pins (scripts/check_image_versions.py): a pin in a workflow must name an # image of the matrix. Not a pre-commit hook: a change to .pre-commit-config.yaml @@ -79,7 +82,7 @@ jobs: - name: Check image pins run: | export PATH="/opt/venv/bin:$PATH" - python3 scripts/check_image_versions.py pins + $OFFLINE python3 scripts/check_image_versions.py pins # A pull request from a renovate/ branch may only move version, tag, digest and pin # lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow @@ -106,8 +109,9 @@ jobs: else echo "::notice::$BASE_REF has no scripts/check_bot_pr_diff.py yet; running the pull request's copy" fi - python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" + $OFFLINE python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" + # Online: a new network namespace has loopback down, and the image has no ip to bring it up for the fake registry. - name: Test the repository scripts run: | export PATH="/opt/venv/bin:$PATH" @@ -125,7 +129,7 @@ jobs: echo "gitleaks binary not found in the pre-commit cache" >&2 exit 1 fi - "$GITLEAKS" git --verbose --redact --log-opts="origin/main..$SHA" + $OFFLINE "$GITLEAKS" git --verbose --redact --log-opts="origin/main..$SHA" # commit-msg stage hooks do not run under --all-files, so each commit's message is given to # every commit-msg hook (Conventional Commits, refuse-agent-trailers); --no-verify skips them locally. @@ -139,5 +143,5 @@ jobs: for sha in $(git rev-list --no-merges "origin/main..$SHA"); do git log -1 --format=%B "$sha" > "$MSG_FILE" echo "Checking $sha" - pre-commit run --hook-stage commit-msg --commit-msg-filename "$MSG_FILE" + $OFFLINE pre-commit run --hook-stage commit-msg --commit-msg-filename "$MSG_FILE" done diff --git a/docs/images/ci.md b/docs/images/ci.md index 5e15584..2d293ed 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -66,7 +66,8 @@ Read `.gitea/workflows/molecule.yml` for the full command. `/opt/ci-pins.sha256` lists the five pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `extensions/molecule/requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and -collections are used as they are. When a pull request changes a pin the check fails and the job installs the pinned +collections are used as they are, and Lint and Build run their tools without network, so a tool that +downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned tools and collections itself for that run (slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml`, `molecule.yml` and `gitea-release-key.yml` are the real consumers. diff --git a/images/AGENTS.md b/images/AGENTS.md index cfc8e02..463b47b 100644 --- a/images/AGENTS.md +++ b/images/AGENTS.md @@ -61,8 +61,9 @@ it to this repository's organisation in the Gitea registry as `` and `l - **Bake in:** every tool, collection, hook environment and package a CI job uses is in its image; a job downloads at run time only on the slow path (a pull request that changes a pin - file). *Why:* a run that downloads is slower and depends on the network. *Held:* review until - the network-off check (#168) lands. + file). *Why:* a run that downloads is slower and depends on the network. *Held:* control: on + the fast path the Lint and Build tool steps run without network, so a download fails the job; + review for the script tests, which keep network, and for Molecule. - **Recorded speed:** a speed optimisation that adds machinery states its measured saving where it lives (a comment next to it). *Why:* machinery is kept only for a saving someone can check. *Held:* review. From 7c148e858d042cf9dba12cd0f83e60b864a1464c Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Thu, 26 Nov 2026 22:20:17 +0000 Subject: [PATCH 04/26] docs: say what the network-off fast path does not hold A step without the $OFFLINE prefix runs online unchecked, and the script tests keep network; both stay held by review. Assisted-by: Claude Code --- .gitea/workflows/AGENTS.md | 5 +++-- docs/images/ci.md | 4 ++-- images/AGENTS.md | 3 ++- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index cc34b0b..c62780d 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -60,8 +60,9 @@ issue. - **On the fast path the tool steps run in a network namespace without network** (`unshare -rn` through `$OFFLINE`), except "Test the repository scripts", whose fake registry needs loopback; the slow path keeps network. *Why:* a runtime download is a bake-in defect and must fail the - job, not silently slow it. *Held:* control: the `$OFFLINE` prefix set by the "Check the baked - tooling against the pins" step. + job, not silently slow it. *Held:* control for the steps that carry the `$OFFLINE` prefix set + by the "Check the baked tooling against the pins" step; review that every new tool step + carries it. - **Triggers:** both run on pull requests to `main` and on manual dispatch; Build also runs on `v*` tags, where it checks the tag against `galaxy.yml`. *Why:* the tag is what consumers install. *Held:* review. diff --git a/docs/images/ci.md b/docs/images/ci.md index 2d293ed..d429449 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -66,8 +66,8 @@ Read `.gitea/workflows/molecule.yml` for the full command. `/opt/ci-pins.sha256` lists the five pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `extensions/molecule/requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and -collections are used as they are, and Lint and Build run their tools without network, so a tool that -downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned +collections are used as they are, and Lint and Build run their tools (all but the script tests) without +network, so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned tools and collections itself for that run (slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml`, `molecule.yml` and `gitea-release-key.yml` are the real consumers. diff --git a/images/AGENTS.md b/images/AGENTS.md index 463b47b..b0e0b31 100644 --- a/images/AGENTS.md +++ b/images/AGENTS.md @@ -63,7 +63,8 @@ it to this repository's organisation in the Gitea registry as `` and `l image; a job downloads at run time only on the slow path (a pull request that changes a pin file). *Why:* a run that downloads is slower and depends on the network. *Held:* control: on the fast path the Lint and Build tool steps run without network, so a download fails the job; - review for the script tests, which keep network, and for Molecule. + review for a new tool step without the prefix, for the script tests, which keep network, and + for Molecule. - **Recorded speed:** a speed optimisation that adds machinery states its measured saving where it lives (a comment next to it). *Why:* machinery is kept only for a saving someone can check. *Held:* review. From d5a91520df720c5a237d03fdf6fa4beef1a0fb96 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Thu, 26 Nov 2026 22:01:43 +0000 Subject: [PATCH 05/26] feat(system_baseline): add inputs that append packages to the profile's lists system_baseline_essential_packages and system_baseline_remove_packages replace the whole list, and so does a list inside system_baseline_profile_overrides, so adding one package meant repeating the profile's list and keeping it in step with every release. system_baseline_extra_packages and system_baseline_extra_remove_packages (lists, default empty) append to the resolved lists. The tmux and unattended-upgrades checks read the combined list, so an extra tmux or unattended-upgrades enables the matching task like a profile package. Items must be Debian package names: a null item would have become the package "None", and apt reads a trailing minus (jq-) as a removal. A package that one input installs and another purges stops the run before any change; only overlaps that involve an extra are checked, so a consumer's own overlap between the resolved lists behaves as before. A flat input that is a plain string still counts as a one-item list. With both inputs left at their default the role behaves as before. Closes #399 Assisted-by: Claude Code:claude-sonnet-5-5 --- changelogs/fragments/399-extra-packages.yml | 8 ++ roles/system_baseline/README.md | 20 ++++- roles/system_baseline/defaults/main.yml | 16 +++- roles/system_baseline/meta/argument_specs.yml | 24 +++++- .../molecule/default/converge.yml | 75 +++++++++++++++++++ .../molecule/default/prepare.yml | 10 ++- .../default/tasks/refuse_extra_packages.yml | 21 ++++++ .../molecule/default/verify.yml | 55 ++++++++++++++ roles/system_baseline/tasks/main.yml | 2 +- roles/system_baseline/tasks/packages.yml | 4 +- roles/system_baseline/tasks/tmux.yml | 11 +-- roles/system_baseline/tasks/validate.yml | 37 +++++++++ 12 files changed, 269 insertions(+), 14 deletions(-) create mode 100644 changelogs/fragments/399-extra-packages.yml create mode 100644 roles/system_baseline/molecule/default/tasks/refuse_extra_packages.yml diff --git a/changelogs/fragments/399-extra-packages.yml b/changelogs/fragments/399-extra-packages.yml new file mode 100644 index 0000000..3e1c6ae --- /dev/null +++ b/changelogs/fragments/399-extra-packages.yml @@ -0,0 +1,8 @@ +--- +minor_changes: + - >- + system_baseline - Add ``system_baseline_extra_packages`` and ``system_baseline_extra_remove_packages`` (lists, default empty), which + append to the resolved package lists, where setting ``system_baseline_essential_packages`` or ``system_baseline_remove_packages`` + replaces the profile's whole list. An extra ``tmux`` or ``unattended-upgrades`` enables the matching task like a profile package. + A package that one input installs and another purges stops the run before any change. With both inputs left at their default the + role behaves as before. diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index 480678a..4878c11 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -35,6 +35,8 @@ templating error instead of the role's own message. | `system_baseline_profile` | derived | no | Active profile after overrides | | `system_baseline_essential_packages` | from profile | no | Packages to install | | `system_baseline_remove_packages` | from profile | no | Packages to purge when present | +| `system_baseline_extra_packages` | `[]` | no | Packages to install in addition to the resolved list; appends, see "Adding packages to a profile" | +| `system_baseline_extra_remove_packages` | `[]` | no | Packages to purge in addition to the resolved list; appends | | `system_baseline_apt_periodic_settings` | from profile | no | Keys for `20auto-upgrades` | | `system_baseline_apt_upgrade` | from profile | no | `safe` or `dist`: how the role upgrades packages (`pve`: `dist`, the Ubuntu profiles: `safe`); see "Apt upgrade mode" | | `system_baseline_unattended_upgrade_settings` | from profile | no | Keys for `50unattended-upgrades` | @@ -130,6 +132,7 @@ The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_ - Converge then applies the `ubuntu_lxc` profile, with tmux autostart and `system_baseline_apt_daily_timeout: 1h`, and only resolves the `pve` and `ubuntu_vm` profiles and a consumer override, asserting the resolved inputs. - Verify checks the installed and removed packages, the journal size cap, the apt settings in `20auto-upgrades` and `50unattended-upgrades`, the locale, and that systemd loaded the `apt-daily.service` timeout. - Verify checks the tmux snippet: root-owned, valid shell, the session and quoted window command, no effect without a terminal, a session name or window command ending in a newline refused, and the file removed when autostart is off. +- Converge refuses bad items in `system_baseline_extra_packages` and `system_baseline_extra_remove_packages` (whitespace, a null, an empty string, a trailing minus, upper case, a bare string) and a package that one input installs and another purges, then applies the `ubuntu_lxc` profile with `jq` as an extra package and `ed` as an extra removal; verify checks that `jq` is installed, `ed` is gone and the profile's packages are still there, and that an extra `tmux` installs the snippet where a flat list without it installs none. - Converge also checks that a bad `system_baseline_apt_tmpdir` (under `/tmp` or `/var/tmp`, relative, with `..`, empty) is refused in the main flow and in the `update` entry point. Verify reads `tasks/update.yml` and checks that the scratch directory is created with mode `0700`, that both apt tasks set `TMPDIR` to it, and that the connection is reset afterwards: the scenario skips the `update` tag, so the upgrade itself never runs there. - Verify runs the `reboot` entry point with `system_baseline_reboot_if_required: false`, without and with `/var/run/reboot-required`, and checks the fact and that the host did not reboot. - The `pve` origins pin is applied to the Ubuntu container and read back with `apt-config dump`, then removed again. The package blacklist is written, read back as a list, left alone by a second run and removed by an empty list. @@ -145,9 +148,22 @@ Not covered: Molecule skips `sysctl`, `secure_tmp`, `update` and `timezone` (no - Policy lives in defaults, not `vars/`, so group_vars and host_vars can override it. - `no_log` is not used: the role handles no secrets. +### Adding packages to a profile + +`system_baseline_essential_packages` and `system_baseline_remove_packages` replace the profile's whole list, and so does a list inside `system_baseline_profile_overrides`. To add or drop a few packages and keep the profile's own, use the two extra lists, which append: + +```yaml +system_baseline_extra_packages: [jq] +system_baseline_extra_remove_packages: [telnet] +``` + +- Each item is a Debian package name: lower-case letters, digits, `+`, `-` and `.`, two or more characters, starting with a letter or digit and not ending in `-` (apt reads a trailing minus as a removal). Anything else stops the run. Duplicates of the profile list are harmless. +- An extra counts wherever the role looks for a package in the list: an extra `tmux` enables the tmux snippet and an extra `unattended-upgrades` the unattended-upgrades tasks, as a profile package does. +- A package that one input installs and another purges stops the run before any change: `system_baseline_extra_packages` against `system_baseline_remove_packages` or `system_baseline_extra_remove_packages`, and `system_baseline_extra_remove_packages` against `system_baseline_essential_packages`. The resolved lists are not checked against each other, so a consumer's own overlap there behaves as before. + ### tmux on SSH login -With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; `pve` never gets the snippet. +With `system_baseline_tmux_autostart: true` an interactive SSH login attaches to the session `system_baseline_tmux_session` (created when missing), so a dropped connection loses nothing. The `ubuntu_lxc` and `ubuntu_vm` profiles install `tmux`; the `pve` profile has none, so it gets the snippet only if `system_baseline_extra_packages` adds `tmux`. ```yaml system_baseline_tmux_autostart: true @@ -157,7 +173,7 @@ system_baseline_tmux_windows: ``` - It is `/etc/profile.d/tmux-autostart.sh`. Every login shell reads that directory, so the snippet itself acts only for an interactive shell (`case $-`) with a terminal and an SSH connection, outside tmux, and without `~/.no-tmux`. `scp`, `sftp`, `ssh host command`, Ansible and `ssh -t host 'bash -lc cmd'` never trigger it. sshd's `ForceCommand` is not used: it applies to every session type and a broken tmux would lock all of them out. Users whose login shell is zsh or fish are not affected, because those shells do not read `/etc/profile.d`. -- The snippet is installed when autostart is on and the resolved package list contains `tmux` (the `ubuntu_lxc` and `ubuntu_vm` profiles). If you override `system_baseline_essential_packages` without it, nothing is installed. +- The snippet is installed when autostart is on and the packages to install contain `tmux`: the `ubuntu_lxc` and `ubuntu_vm` profiles have it, and `system_baseline_extra_packages` can add it. If you override `system_baseline_essential_packages` without it and add no extra `tmux`, nothing is installed. - A failed attach (for example a client `TERM` such as `xterm-kitty` or `wezterm` without a terminfo entry on the host) prints a line and leaves a plain shell. Detaching (`Ctrl-b d`) ends the SSH connection, as `exit` would. - Turn it off for one login with `ssh -t host bash` (a non-login shell does not read `/etc/profile.d`), for one user with `touch ~/.no-tmux`, and for the host by setting the variable to `false` and running the role (it removes the snippet). - The windows are made when the session is created; a login that re-attaches adds none, so a change applies from the next new session. A window closes when its command exits. A window command runs with `sh -c` from the tmux server of the first login, before `~/.profile` is read, so it does not see `~/.local/bin` and other additions made there: use absolute paths. diff --git a/roles/system_baseline/defaults/main.yml b/roles/system_baseline/defaults/main.yml index 53ab949..1a39db4 100644 --- a/roles/system_baseline/defaults/main.yml +++ b/roles/system_baseline/defaults/main.yml @@ -21,7 +21,8 @@ system_baseline_update: true # Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it. system_baseline_journal_max_use: 200M # Attach an interactive SSH login to a tmux session (see tasks/tmux.yml). Off by default: it changes what every login does. -# Only the ubuntu_lxc and ubuntu_vm profiles honour it; pve never installs the snippet. +# Installed only when tmux is among the packages to install: the ubuntu_lxc and ubuntu_vm profiles have it, the pve profile has none unless +# system_baseline_extra_packages adds it. system_baseline_tmux_autostart: false # Name of the session an SSH login attaches to. system_baseline_tmux_session: main @@ -246,6 +247,19 @@ system_baseline_profile: >- # Inputs the tasks read system_baseline_essential_packages: "{{ system_baseline_profile.essential_packages }}" system_baseline_remove_packages: "{{ system_baseline_profile.remove_packages }}" +# Packages installed and purged in addition to the two resolved lists above. They append: a flat essential or remove input replaces its +# list, so adding one package that way means repeating the whole profile list. +system_baseline_extra_packages: [] +system_baseline_extra_remove_packages: [] +# What the role acts on: each resolved list plus its extras, without duplicates. Internal, read by tasks/packages.yml, tasks/tmux.yml and +# tasks/main.yml, so that an extra `tmux` or `unattended-upgrades` enables the matching task like a profile package does. +# A flat input that is a plain string (`system_baseline_essential_packages: vim`, which the package module accepts) counts as a one-item list. +__system_baseline_install_packages: >- + {{ (([system_baseline_essential_packages] if system_baseline_essential_packages is string else system_baseline_essential_packages) + + system_baseline_extra_packages) | unique | list }} +__system_baseline_purge_packages: >- + {{ (([system_baseline_remove_packages] if system_baseline_remove_packages is string else system_baseline_remove_packages) + + system_baseline_extra_remove_packages) | unique | list }} system_baseline_apt_periodic_settings: "{{ system_baseline_profile.apt_periodic_settings }}" # safe or dist (see the profiles). Guarded: the tasks_from: update entry point needs no system_baseline_system_type, and without one it # stays on a safe upgrade instead of failing on the profile lookup. default('safe'): a system_baseline_profiles written before this key diff --git a/roles/system_baseline/meta/argument_specs.yml b/roles/system_baseline/meta/argument_specs.yml index 6f36c6b..9f0e417 100644 --- a/roles/system_baseline/meta/argument_specs.yml +++ b/roles/system_baseline/meta/argument_specs.yml @@ -63,7 +63,8 @@ argument_specs: Attach an interactive SSH login to a tmux session, creating it when it does not exist. Installs C(/etc/profile.d/tmux-autostart.sh), which acts only for an interactive login shell with a terminal, so scp, sftp, C(ssh host command) and automation are unaffected. Shells that do not read C(/etc/profile.d) (zsh, fish) are unaffected too. A user opts out with C(~/.no-tmux). Installed only when - C(tmux) is in the resolved package list (the C(ubuntu_lxc) and C(ubuntu_vm) profiles); with false, or without tmux, the file is + C(tmux) is among the packages to install (the C(ubuntu_lxc) and C(ubuntu_vm) profiles have it, and C(system_baseline_extra_packages) + can add it to any profile, C(pve) included); with false, or without tmux, the file is removed. A failed attach leaves a plain shell; detaching ends the SSH connection. system_baseline_tmux_session: type: str @@ -152,6 +153,27 @@ argument_specs: A non-empty list is written to C(/etc/apt/apt.conf.d/90unattended-upgrades-blacklist) as C(Unattended-Upgrade::Package-Blacklist). apt appends list entries across files, so these are added to those of C(50unattended-upgrades). An empty list removes the file. An entry may not hold a double quote, a backslash or a line break. + system_baseline_extra_packages: + type: list + elements: str + default: [] + description: + - >- + Packages installed in addition to the resolved C(system_baseline_essential_packages). The list appends: setting + C(system_baseline_essential_packages) itself replaces the profile's list. A package named here also counts for the checks that read + the package list (C(tmux) for the tmux snippet, C(unattended-upgrades) for the unattended-upgrades tasks). Each item is a Debian + package name: lower-case letters, digits, C(+), C(-) and C(.), two or more characters, starting with a letter or digit and not + ending in C(-) (apt reads a trailing minus as a removal). A package that is also in C(system_baseline_remove_packages) or + C(system_baseline_extra_remove_packages) stops the run before any change. + system_baseline_extra_remove_packages: + type: list + elements: str + default: [] + description: + - >- + Packages purged, when installed, in addition to the resolved C(system_baseline_remove_packages). The list appends. Each item is a + Debian package name, as for C(system_baseline_extra_packages). A package that is also in C(system_baseline_essential_packages) + stops the run before any change. system_baseline_update: type: bool default: true diff --git a/roles/system_baseline/molecule/default/converge.yml b/roles/system_baseline/molecule/default/converge.yml index 437f61b..0a0b4d8 100644 --- a/roles/system_baseline/molecule/default/converge.yml +++ b/roles/system_baseline/molecule/default/converge.yml @@ -133,11 +133,38 @@ - [null] - linux-image-.* +# Items that are not Debian package names (whitespace, null, empty, a trailing minus that apt reads as a removal, an option, upper case, a +# version pin), and a package that one input installs and another purges, each stop the run before any change. +# The overlaps are: an extra install against the profile's remove list (telnet), an extra install against an extra remove, and an extra +# remove against the profile's install list (tmux). +- name: A bad extra package list is refused + hosts: all + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_extra_packages.yml + vars: + system_baseline_refused_case: "{{ item }}" + loop: + - { install: ['bad name'], expect: 'must be lists of package names' } + - { install: [null], expect: 'must be lists of package names' } + - { install: jq, expect: 'must be lists of package names' } + - { remove: [''], expect: 'must be lists of package names' } + - { install: ['jq-'], expect: 'must be lists of package names' } + - { install: ['-y'], expect: 'must be lists of package names' } + - { remove: ['Telnet'], expect: 'must be lists of package names' } + - { remove: ['ed=1.0'], expect: 'must be lists of package names' } + - { install: [telnet], expect: 'is both installed and purged' } + - { install: [jq], remove: [jq], expect: 'is both installed and purged' } + - { remove: [tmux], expect: 'is both installed and purged' } + - name: Converge the LXC profile hosts: all gather_facts: true vars: system_baseline_system_type: ubuntu_lxc + system_baseline_extra_packages: [jq] + system_baseline_extra_remove_packages: [ed] system_baseline_tmux_autostart: true system_baseline_apt_daily_timeout: 1h system_baseline_tmux_session: molecule @@ -172,6 +199,8 @@ - system_baseline_apt_upgrade == 'dist' - system_baseline_unattended_upgrade_origins | length == 3 - system_baseline_unattended_upgrade_origins | select('search', 'Proxmox') | list == [] + - __system_baseline_install_packages == system_baseline_essential_packages + - __system_baseline_purge_packages == system_baseline_remove_packages quiet: true - name: The ubuntu_vm profile resolves @@ -195,6 +224,8 @@ - system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1 - system_baseline_apt_upgrade == 'safe' - system_baseline_unattended_upgrade_origins == [] + - __system_baseline_install_packages == system_baseline_essential_packages + - __system_baseline_purge_packages == system_baseline_remove_packages quiet: true # Consumer play vars override the profile. @@ -224,3 +255,47 @@ - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' - "'qemu-guest-agent' in system_baseline_essential_packages" quiet: true + +# The extras append to the resolved lists, whether the profile's list or a flat input supplies them, and a name that is in both is listed once. +- name: Extra packages append to the resolved lists + hosts: all + gather_facts: false + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_essential_packages: [vim, curl] + system_baseline_extra_packages: [jq, vim, unattended-upgrades] + system_baseline_extra_remove_packages: [ed, telnet] + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the lists the role acts on + ansible.builtin.assert: + that: + - __system_baseline_install_packages == ['vim', 'curl', 'jq', 'unattended-upgrades'] + - "'ed' in __system_baseline_purge_packages" + - __system_baseline_purge_packages | select('equalto', 'telnet') | list | length == 1 + - system_baseline_remove_packages | difference(__system_baseline_purge_packages) | length == 0 + quiet: true + +# A flat input that is a plain string (the package module accepts one) still counts as a one-item list, with and without extras. +- name: A flat string package list still resolves + hosts: all + gather_facts: false + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_essential_packages: vim + system_baseline_extra_packages: [jq] + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the lists the role acts on + ansible.builtin.assert: + that: + - __system_baseline_install_packages == ['vim', 'jq'] + quiet: true diff --git a/roles/system_baseline/molecule/default/prepare.yml b/roles/system_baseline/molecule/default/prepare.yml index 3b41e7b..c7b6152 100644 --- a/roles/system_baseline/molecule/default/prepare.yml +++ b/roles/system_baseline/molecule/default/prepare.yml @@ -1,12 +1,18 @@ --- # A package the role must remove, and the locales tool the role assumes exists -# (it does on a stock Ubuntu host). +# (it does on a stock Ubuntu host). jq (system_baseline_extra_packages) must be absent, so that the role is what installs it, and ed +# (system_baseline_extra_remove_packages, on no profile list) must be present, so that the role is what purges it. - name: Prepare hosts: all gather_facts: false tasks: - name: Install a package on the role's remove list and locale-gen ansible.builtin.apt: - name: [telnet, locales] + name: [telnet, locales, ed] state: present update_cache: true + + - name: Make sure jq is not installed + ansible.builtin.apt: + name: jq + state: absent diff --git a/roles/system_baseline/molecule/default/tasks/refuse_extra_packages.yml b/roles/system_baseline/molecule/default/tasks/refuse_extra_packages.yml new file mode 100644 index 0000000..bf3ac1c --- /dev/null +++ b/roles/system_baseline/molecule/default/tasks/refuse_extra_packages.yml @@ -0,0 +1,21 @@ +--- +# One refusal per call: the role must stop on validation, before it changes anything, with a message that names the inputs. +# The case comes in as system_baseline_refused_case: {install, remove, expect}. +- name: Run the role with a bad extra package list + block: + - name: Include system_baseline + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_extra_packages: "{{ system_baseline_refused_case.install | default([]) }}" + system_baseline_extra_remove_packages: "{{ system_baseline_refused_case.remove | default([]) }}" + - name: Unreachable when validation works + ansible.builtin.fail: + msg: system_baseline ran with a bad extra package list + rescue: + - name: The validation stopped the play with the expected message + ansible.builtin.assert: + that: system_baseline_refused_case.expect in ansible_failed_result.msg | default('') + fail_msg: "Expected '{{ system_baseline_refused_case.expect }}', got: {{ ansible_failed_result.msg | default('') }}" + quiet: true diff --git a/roles/system_baseline/molecule/default/verify.yml b/roles/system_baseline/molecule/default/verify.yml index d2eb81a..bc0dca2 100644 --- a/roles/system_baseline/molecule/default/verify.yml +++ b/roles/system_baseline/molecule/default/verify.yml @@ -17,6 +17,16 @@ - "'telnet' not in ansible_facts.packages" quiet: true + # jq was absent before the role ran and is on no profile list: the extra list installed it, and the profile's own packages (tmux, + # curl above) are still there. ed was present and is on no profile list: the extra remove list purged it. + - name: The extra packages were installed and the extra removal purged + ansible.builtin.assert: + that: + - "'jq' in ansible_facts.packages" + - "'curl' in ansible_facts.packages" + - "'ed' not in ansible_facts.packages" + quiet: true + - name: Read the journald drop-in ansible.builtin.slurp: src: /etc/systemd/journald.conf.d/50-system-baseline.conf @@ -254,6 +264,51 @@ that: not system_baseline_verify_removed.stat.exists quiet: true + # An extra tmux counts like a profile tmux: a flat package list without it installs no snippet, the same list plus the extra does. + - name: Run the tmux tasks with a flat package list that lacks tmux + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: tmux + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: true + system_baseline_essential_packages: [vim] + + - name: Stat the snippet without the extra + ansible.builtin.stat: + path: /etc/profile.d/tmux-autostart.sh + register: system_baseline_verify_no_extra + + - name: Run the tmux tasks with tmux as an extra package + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: tmux + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: true + system_baseline_essential_packages: [vim] + system_baseline_extra_packages: [tmux] + + - name: Stat the snippet with the extra + ansible.builtin.stat: + path: /etc/profile.d/tmux-autostart.sh + register: system_baseline_verify_with_extra + + - name: Only the extra tmux installs the snippet + ansible.builtin.assert: + that: + - not system_baseline_verify_no_extra.stat.exists + - system_baseline_verify_with_extra.stat.exists + quiet: true + + - name: Remove the snippet again + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: tmux + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_tmux_autostart: false + # The pve origins pin, run on this Ubuntu host: Ubuntu's 50unattended-upgrades sets Allowed-Origins, so the merged # configuration showing only the pinned patterns proves the drop-in clears the earlier lists instead of appending to them. # The patterns match no Ubuntu origin, which only means nothing would be upgraded; the role's dry run still passes. Here diff --git a/roles/system_baseline/tasks/main.yml b/roles/system_baseline/tasks/main.yml index 46bb026..0917c46 100644 --- a/roles/system_baseline/tasks/main.yml +++ b/roles/system_baseline/tasks/main.yml @@ -17,7 +17,7 @@ - name: Configure unattended-upgrades ansible.builtin.import_tasks: unattended_upgrades.yml - when: "'unattended-upgrades' in system_baseline_essential_packages" + when: "'unattended-upgrades' in __system_baseline_install_packages" tags: unattended-upgrades - name: Set locale diff --git a/roles/system_baseline/tasks/packages.yml b/roles/system_baseline/tasks/packages.yml index a10df06..1439741 100644 --- a/roles/system_baseline/tasks/packages.yml +++ b/roles/system_baseline/tasks/packages.yml @@ -1,7 +1,7 @@ --- - name: Install essential packages ansible.builtin.package: - name: "{{ system_baseline_essential_packages }}" + name: "{{ __system_baseline_install_packages }}" state: present update_cache: true become: true @@ -16,6 +16,6 @@ name: "{{ item }}" state: absent purge: true - loop: "{{ system_baseline_remove_packages }}" + loop: "{{ __system_baseline_purge_packages }}" when: item in ansible_facts.packages become: true diff --git a/roles/system_baseline/tasks/tmux.yml b/roles/system_baseline/tasks/tmux.yml index fde0c8c..27e1758 100644 --- a/roles/system_baseline/tasks/tmux.yml +++ b/roles/system_baseline/tasks/tmux.yml @@ -4,9 +4,10 @@ # connection, so scp, sftp, `ssh host command` and automation never trigger it. # sshd's ForceCommand is deliberately not used: it applies to every session type and a broken tmux would lock out all of them. # -# Installed when autostart is on and the resolved package list holds tmux (the ubuntu_lxc and ubuntu_vm profiles); the inputs are -# checked in validate.yml. Security: the session name, window names and commands are role inputs (inventory), never read from a user -# or a fact. They are validated and shell-quoted in the template. The script is root-owned and not writable by the users it runs for. +# Installed when autostart is on and the packages to install hold tmux (the ubuntu_lxc and ubuntu_vm profiles, or +# system_baseline_extra_packages); the inputs are checked in validate.yml. Security: the session name, window names and commands are +# role inputs (inventory), never read from a user or a fact. They are validated and shell-quoted in the template. The script is +# root-owned and not writable by the users it runs for. # It is world-readable and the commands show in `ps`, so a command must hold no secret. Commands run as the user who logs in. - name: Install the tmux auto-start snippet ansible.builtin.template: @@ -16,12 +17,12 @@ group: root mode: "0644" validate: /bin/sh -n %s - when: system_baseline_tmux_autostart | bool and 'tmux' in system_baseline_essential_packages + when: system_baseline_tmux_autostart | bool and 'tmux' in __system_baseline_install_packages become: true - name: Remove the tmux auto-start snippet ansible.builtin.file: path: /etc/profile.d/tmux-autostart.sh state: absent - when: not (system_baseline_tmux_autostart | bool and 'tmux' in system_baseline_essential_packages) + when: not (system_baseline_tmux_autostart | bool and 'tmux' in __system_baseline_install_packages) become: true diff --git a/roles/system_baseline/tasks/validate.yml b/roles/system_baseline/tasks/validate.yml index 20d78c3..b9d054b 100644 --- a/roles/system_baseline/tasks/validate.yml +++ b/roles/system_baseline/tasks/validate.yml @@ -75,6 +75,43 @@ quiet: true tags: always +# The extras are appended to the resolved lists. An item must be a Debian package name (policy: lower-case letters, digits, + - . , two or +# more characters, starting with a letter or digit), and not end in a minus: apt reads `jq-` as "remove jq", and a null item would become the +# package "None". A bare string is rejected here as it is for the blacklist. A package that one input installs and another purges would be +# installed and removed on every run, so it stops the run; only overlaps that involve an extra are checked, the resolved lists themselves +# are the consumer's. +- name: Validate the extra packages + ansible.builtin.assert: + that: + - system_baseline_extra_packages is sequence + - system_baseline_extra_packages is not string + - system_baseline_extra_packages is not mapping + - system_baseline_extra_packages | select('string') | select('match', '^[a-z0-9][a-z0-9+.-]*[a-z0-9+.]\Z') | list | length + == system_baseline_extra_packages | length + - system_baseline_extra_remove_packages is sequence + - system_baseline_extra_remove_packages is not string + - system_baseline_extra_remove_packages is not mapping + - system_baseline_extra_remove_packages | select('string') | select('match', '^[a-z0-9][a-z0-9+.-]*[a-z0-9+.]\Z') | list | length + == system_baseline_extra_remove_packages | length + fail_msg: >- + system_baseline_extra_packages and system_baseline_extra_remove_packages must be lists of package names: lower-case letters, + digits, + - . only, two or more characters, starting with a letter or digit and not ending in a minus. + quiet: true + tags: always + +- name: Refuse a package that is both installed and purged + ansible.builtin.assert: + that: + - system_baseline_extra_packages | intersect(__system_baseline_purge_packages) | length == 0 + - system_baseline_extra_remove_packages | intersect(__system_baseline_install_packages) | length == 0 + fail_msg: >- + A package is both installed and purged. system_baseline_extra_packages must not name a package of system_baseline_remove_packages or + system_baseline_extra_remove_packages, and system_baseline_extra_remove_packages must not name a package of + system_baseline_essential_packages. Found: {{ (system_baseline_extra_packages | intersect(__system_baseline_purge_packages)) + + (system_baseline_extra_remove_packages | intersect(__system_baseline_install_packages)) }}. + quiet: true + tags: always + # Each origin is written inside a double-quoted apt.conf string: a quote or a line break would end it, a backslash could escape. - name: Validate the unattended-upgrades origins ansible.builtin.assert: From 4d5042a31fd53e8ec9f25673855a37a5cd5a8bac Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Thu, 26 Nov 2026 22:48:51 +0000 Subject: [PATCH 06/26] ci: cut the fast-path network by environment, not unshare The runner's job container refuses unshare, even with a user namespace, so the fast path sets PIP_NO_INDEX and a dead proxy instead; a raw socket is not caught. Assisted-by: Claude Code --- .gitea/workflows/AGENTS.md | 14 ++++++++------ .gitea/workflows/build.yml | 18 ++++++++++-------- .gitea/workflows/lint.yml | 21 ++++++++++++--------- docs/images/ci.md | 4 ++-- images/AGENTS.md | 6 +++--- 5 files changed, 35 insertions(+), 28 deletions(-) diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index c62780d..9250962 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -57,12 +57,14 @@ issue. `.pre-commit-config.yaml` takes the slow path, which installs the pinned tools and collections. *Why:* a pull request is tested on its own pins, and an unchanged one starts in seconds. *Held:* control: the "Check the baked tooling against the pins" step. -- **On the fast path the tool steps run in a network namespace without network** (`unshare -rn` - through `$OFFLINE`), except "Test the repository scripts", whose fake registry needs loopback; - the slow path keeps network. *Why:* a runtime download is a bake-in defect and must fail the - job, not silently slow it. *Held:* control for the steps that carry the `$OFFLINE` prefix set - by the "Check the baked tooling against the pins" step; review that every new tool step - carries it. +- **On the fast path the network is cut by environment**: `PIP_NO_INDEX=1`, the proxy variables + set to a dead local port and `no_proxy` empty, for every later step except "Test the repository + scripts", which unsets them for its fake registry on loopback; the slow path keeps network. + *Why:* a runtime download is a bake-in defect and must fail the job, not silently slow it. + *Held:* control, set by the "Check the baked tooling against the pins" step, for pip, curl, git + over HTTPS and Python's urllib or requests (anything honouring `PIP_NO_INDEX` or the proxy + variables); review for a raw socket or a tool that ignores the proxy variables, and for the + script tests. - **Triggers:** both run on pull requests to `main` and on manual dispatch; Build also runs on `v*` tags, where it checks the tag against `galaxy.yml`. *Why:* the tag is what consumers install. *Held:* review. diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index a71904c..3ac55be 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -60,9 +60,11 @@ jobs: run: | if sha256sum --quiet -c /opt/ci-pins.sha256; then echo "The pin files match the ci image; using the baked tools." - # -r adds a user namespace: a job container lacks CAP_SYS_ADMIN for a plain unshare -n. - echo "OFFLINE=unshare -rn --" >> "$GITHUB_ENV" - echo "::notice::The tool steps run without network; a download fails the job (bake it into images/ci)." + # A job container may not unshare, so the network is cut by environment: pip, curl, + # git over HTTPS and Python's urllib fail; a raw socket is not caught. + printf '%s\n' PIP_NO_INDEX=1 http_proxy=http://127.0.0.1:9 https_proxy=http://127.0.0.1:9 \ + HTTP_PROXY=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 no_proxy= NO_PROXY= >> "$GITHUB_ENV" + echo "::notice::Later steps run with a dead proxy; a download fails the job (bake it into images/ci)." else echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \ "extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \ @@ -82,7 +84,7 @@ jobs: echo "::error::$TAG is a lightweight tag; releases must be annotated (git tag -a)" exit 1 fi - version="$($OFFLINE python3 -c 'import sys, yaml; print(yaml.safe_load(open("galaxy.yml"))["version"])')" + version="$(python3 -c 'import sys, yaml; print(yaml.safe_load(open("galaxy.yml"))["version"])')" if [ "$TAG" != "v$version" ]; then echo "::error::tag $TAG does not match galaxy.yml version $version (expected v$version)" exit 1 @@ -109,7 +111,7 @@ jobs: run: | export PATH="/opt/venv/bin:$PATH" mkdir -p /tmp/dist - $OFFLINE ansible-galaxy collection build --force --output-path /tmp/dist . + ansible-galaxy collection build --force --output-path /tmp/dist . ls -l /tmp/dist sha256sum /tmp/dist/*.tar.gz @@ -122,7 +124,7 @@ jobs: echo "::error::expected exactly one tarball in /tmp/dist, found $# match(es): $*" exit 1 fi - $OFFLINE python3 scripts/check_tarball.py "$1" + python3 scripts/check_tarball.py "$1" # galaxy-importer without ansible-test and without Docker. The importer reads its # configuration from this file. @@ -141,7 +143,7 @@ jobs: exit 1 fi GALAXY_IMPORTER_CONFIG=/tmp/galaxy-importer.cfg \ - $OFFLINE python3 -m galaxy_importer.main "$1" + python3 -m galaxy_importer.main "$1" # Sanity tests need the collection at ansible_collections//. - name: Run ansible-test sanity @@ -162,4 +164,4 @@ jobs: { cat tests/sanity/ignore-common.txt; if [ -f "$ignore" ]; then cat "$ignore"; fi; } > /tmp/ignore.new mv /tmp/ignore.new "$ignore" echo "Sanity ignore list for ansible-core ${core}: $(wc -l < "$ignore") lines" - $OFFLINE ansible-test sanity --requirements --color no + ansible-test sanity --requirements --color no diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index a6f65a2..a069946 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -59,9 +59,11 @@ jobs: run: | if sha256sum --quiet -c /opt/ci-pins.sha256; then echo "The pin files match the ci image; using the baked tools." - # -r adds a user namespace: a job container lacks CAP_SYS_ADMIN for a plain unshare -n. - echo "OFFLINE=unshare -rn --" >> "$GITHUB_ENV" - echo "::notice::The tool steps run without network; a download fails the job (bake it into images/ci)." + # A job container may not unshare, so the network is cut by environment: pip, curl, + # git over HTTPS and Python's urllib fail; a raw socket is not caught. + printf '%s\n' PIP_NO_INDEX=1 http_proxy=http://127.0.0.1:9 https_proxy=http://127.0.0.1:9 \ + HTTP_PROXY=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 no_proxy= NO_PROXY= >> "$GITHUB_ENV" + echo "::notice::Later steps run with a dead proxy; a download fails the job (bake it into images/ci)." else echo "::warning::requirements-dev.txt, requirements-dev.lock, requirements.yml," \ "extensions/molecule/requirements.yml or .pre-commit-config.yaml differ from the ci image;" \ @@ -74,7 +76,7 @@ jobs: - name: Run pre-commit on all files run: | export PATH="/opt/venv/bin:$PATH" - $OFFLINE pre-commit run --all-files --show-diff-on-failure + pre-commit run --all-files --show-diff-on-failure # Image pins (scripts/check_image_versions.py): a pin in a workflow must name an # image of the matrix. Not a pre-commit hook: a change to .pre-commit-config.yaml @@ -82,7 +84,7 @@ jobs: - name: Check image pins run: | export PATH="/opt/venv/bin:$PATH" - $OFFLINE python3 scripts/check_image_versions.py pins + python3 scripts/check_image_versions.py pins # A pull request from a renovate/ branch may only move version, tag, digest and pin # lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow @@ -109,11 +111,12 @@ jobs: else echo "::notice::$BASE_REF has no scripts/check_bot_pr_diff.py yet; running the pull request's copy" fi - $OFFLINE python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" + python3 -E -s "$guard" "$HEAD_REF" "$BASE_REF" - # Online: a new network namespace has loopback down, and the image has no ip to bring it up for the fake registry. + # Without the guard: an empty no_proxy would send the fake registry on 127.0.0.1 to the dead proxy. - name: Test the repository scripts run: | + unset PIP_NO_INDEX http_proxy https_proxy HTTP_PROXY HTTPS_PROXY export PATH="/opt/venv/bin:$PATH" python3 -m unittest discover -s tests/scripts @@ -129,7 +132,7 @@ jobs: echo "gitleaks binary not found in the pre-commit cache" >&2 exit 1 fi - $OFFLINE "$GITLEAKS" git --verbose --redact --log-opts="origin/main..$SHA" + "$GITLEAKS" git --verbose --redact --log-opts="origin/main..$SHA" # commit-msg stage hooks do not run under --all-files, so each commit's message is given to # every commit-msg hook (Conventional Commits, refuse-agent-trailers); --no-verify skips them locally. @@ -143,5 +146,5 @@ jobs: for sha in $(git rev-list --no-merges "origin/main..$SHA"); do git log -1 --format=%B "$sha" > "$MSG_FILE" echo "Checking $sha" - $OFFLINE pre-commit run --hook-stage commit-msg --commit-msg-filename "$MSG_FILE" + pre-commit run --hook-stage commit-msg --commit-msg-filename "$MSG_FILE" done diff --git a/docs/images/ci.md b/docs/images/ci.md index d429449..ad9b1bd 100644 --- a/docs/images/ci.md +++ b/docs/images/ci.md @@ -66,8 +66,8 @@ Read `.gitea/workflows/molecule.yml` for the full command. `/opt/ci-pins.sha256` lists the five pin files by their checkout-relative path, so `sha256sum -c` runs in the checkout root. When the checkout's `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `extensions/molecule/requirements.yml` and `.pre-commit-config.yaml` match, the baked tools and -collections are used as they are, and Lint and Build run their tools (all but the script tests) without -network, so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned +collections are used as they are, and Lint and Build cut the network by environment (proxy variables and +`PIP_NO_INDEX`) for all but the script tests, so a tool that downloads at run time fails the job. When a pull request changes a pin the check fails and the job installs the pinned tools and collections itself for that run (slower, same result), until the image is rebuilt from `main`. `lint.yml`, `build.yml`, `molecule.yml` and `gitea-release-key.yml` are the real consumers. diff --git a/images/AGENTS.md b/images/AGENTS.md index b0e0b31..c22eb58 100644 --- a/images/AGENTS.md +++ b/images/AGENTS.md @@ -62,9 +62,9 @@ it to this repository's organisation in the Gitea registry as `` and `l - **Bake in:** every tool, collection, hook environment and package a CI job uses is in its image; a job downloads at run time only on the slow path (a pull request that changes a pin file). *Why:* a run that downloads is slower and depends on the network. *Held:* control: on - the fast path the Lint and Build tool steps run without network, so a download fails the job; - review for a new tool step without the prefix, for the script tests, which keep network, and - for Molecule. + the fast path Lint and Build cut the network by environment, so a download through pip or a + proxy-honouring client fails the job; review for a raw socket, for the script tests, which keep + network, and for Molecule. - **Recorded speed:** a speed optimisation that adds machinery states its measured saving where it lives (a comment next to it). *Why:* machinery is kept only for a saving someone can check. *Held:* review. From 11fec7c8fc73f10403d7185f58a85ae29792f876 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Thu, 26 Nov 2026 23:03:51 +0000 Subject: [PATCH 07/26] ci: rerun the molecule job to capture the scenario logs The molecule job of the previous head ended at its timeout before it printed the per-scenario logs, so the exit 2 of pihole and user_management has no output. No file changes. Assisted-by: Claude Code:claude-sonnet-5-5 From 3a5040aae8c652754f73ad2c9e26dea8457aa804 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Thu, 26 Nov 2026 23:58:23 +0000 Subject: [PATCH 08/26] fix: read getent results through ansible_facts in two verify plays The pihole and user_management scenarios read getent_passwd and getent_shadow as top-level variables. The getent module returns them as facts, which are injected as variables only while inject_facts_as_vars is on, so with the setting this pull request turns on in the molecule job the two verify plays failed (exit 2 in both runs of this pull request, whose per-scenario logs were not printed). They now read ansible_facts['getent_passwd'] and ansible_facts['getent_shadow']. The remaining module-returned facts in roles/ and extensions/ (package_facts, service_facts, the getent read in user_management's ssh_keys.yml) are already read through ansible_facts. Assisted-by: Claude Code:claude-sonnet-5-5 --- roles/pihole/molecule/default/verify.yml | 4 ++-- roles/user_management/molecule/default/verify.yml | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/roles/pihole/molecule/default/verify.yml b/roles/pihole/molecule/default/verify.yml index be5b64f..284c2bd 100644 --- a/roles/pihole/molecule/default/verify.yml +++ b/roles/pihole/molecule/default/verify.yml @@ -98,8 +98,8 @@ - name: The user is a system account without a login shell ansible.builtin.assert: that: - - getent_passwd.pihole[5] == '/usr/sbin/nologin' - - getent_passwd.pihole[1] | int < 1000 + - ansible_facts['getent_passwd'].pihole[5] == '/usr/sbin/nologin' + - ansible_facts['getent_passwd'].pihole[1] | int < 1000 quiet: true # Neither check run (before and after the converge) ran the installer or the handler. diff --git a/roles/user_management/molecule/default/verify.yml b/roles/user_management/molecule/default/verify.yml index 0b1c96b..567e27e 100644 --- a/roles/user_management/molecule/default/verify.yml +++ b/roles/user_management/molecule/default/verify.yml @@ -9,7 +9,7 @@ - name: The removed user is gone ansible.builtin.assert: - that: "'um-olduser' not in getent_passwd" + that: "'um-olduser' not in ansible_facts['getent_passwd']" quiet: true - name: Read group membership @@ -74,7 +74,7 @@ ansible.builtin.assert: that: - user_management_test_admin_key in (user_management_verify_keys.results[0].content | b64decode) - - getent_passwd['um-admin'][5] != '/usr/sbin/nologin' + - ansible_facts['getent_passwd']['um-admin'][5] != '/usr/sbin/nologin' quiet: true - name: Read root's shadow entry @@ -86,7 +86,7 @@ - name: Root's password is locked ansible.builtin.assert: that: - - getent_shadow['root'][0] == '!' + - ansible_facts['getent_shadow']['root'][0] == '!' quiet: true - name: Read root's authorized_keys @@ -98,5 +98,5 @@ ansible.builtin.assert: that: - (user_management_verify_root_keys.content | b64decode) is search('root-key$', multiline=true) - - getent_passwd['root'][5] == '/bin/bash' + - ansible_facts['getent_passwd']['root'][5] == '/bin/bash' quiet: true From 2eb7da3563714104a346b90d85194286ea78f6f6 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 27 Nov 2026 03:18:31 +0000 Subject: [PATCH 09/26] chore(deps): update dependency apm-cli to v0.38.1 --- requirements-dev.lock | 6 +++--- requirements-dev.txt | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 9917e06..01494c7 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -240,9 +240,9 @@ anyio==4.16.0 \ # via # httpx2 # openai -apm-cli==0.38.0 \ - --hash=sha256:6dfac2fdc8ab68586afb2b1a5a6db3c1b7ab569ff0edc525448aa85d0f92bd38 \ - --hash=sha256:aa51a98867ae6aef11e92143dd9ca2a994d3dd6cbd7224eae58fb7b8078fc3b1 +apm-cli==0.38.1 \ + --hash=sha256:c2a0394643e54d3516efefcd78bb043509ac48b65cca1f40166023789b8eb89a \ + --hash=sha256:c2ddd1ea95f7223de2ced83c1bbb61b756a10de2651edc76b93346c925dc162b # via -r requirements-dev.txt attrs==23.2.0 \ --hash=sha256:935dc3b529c262f6cf76e50877d35a4bd3c1de194fd41f47a2b7ae8f19971f30 \ diff --git a/requirements-dev.txt b/requirements-dev.txt index 0aa4b6f..d8d8ec5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -19,4 +19,4 @@ molecule-plugins[docker]==26.11.0 proxmoxer==2.3.0 # apm-cli: for changing apm.yml (run apm install, commit the lock). Keep it at 0.36.1 or later (#252): # before 0.29.0, `apm audit --ci` compares the whole .claude/settings.json and fails on any hand-written key. -apm-cli==0.38.0 +apm-cli==0.38.1 From c51fa998b9ff2c5176b5eaf9d6591352871583b7 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Fri, 27 Nov 2026 06:00:04 +0000 Subject: [PATCH 10/26] feat(system_baseline): let system_baseline_journal_max_use be empty to leave journald alone The role capped the persistent journal on every host with no way to opt out, and wrote the value into the drop-in unchecked: an empty value produced an empty SystemMaxUse=, and a bare number, a typo or a line break went into the file as it was. An empty system_baseline_journal_max_use now skips the journald task, as an empty system_baseline_apt_daily_timeout skips its task: no drop-in directory, no drop-in file and no restart of systemd-journald. A file an earlier run wrote stays. Any other value is checked before any change: infinity, or a number followed by K, M, G or T. A bare number, a space and a line break stop the run with a message that names the input. The default stays 200M. Closes #401 Assisted-by: Claude Code:claude-sonnet-5-5 --- .../fragments/401-journal-max-use-empty.yml | 9 ++++ roles/system_baseline/README.md | 9 +++- roles/system_baseline/defaults/main.yml | 3 +- roles/system_baseline/meta/argument_specs.yml | 4 ++ .../molecule/default/converge.yml | 18 ++++++++ .../default/tasks/refuse_journal_max_use.yml | 18 ++++++++ .../molecule/default/verify.yml | 45 +++++++++++++++++++ roles/system_baseline/tasks/main.yml | 1 + roles/system_baseline/tasks/validate.yml | 13 ++++++ 9 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 changelogs/fragments/401-journal-max-use-empty.yml create mode 100644 roles/system_baseline/molecule/default/tasks/refuse_journal_max_use.yml diff --git a/changelogs/fragments/401-journal-max-use-empty.yml b/changelogs/fragments/401-journal-max-use-empty.yml new file mode 100644 index 0000000..0fd9461 --- /dev/null +++ b/changelogs/fragments/401-journal-max-use-empty.yml @@ -0,0 +1,9 @@ +--- +minor_changes: + - >- + system_baseline - ``system_baseline_journal_max_use`` can be empty to leave journald alone: the role then writes no drop-in and does not + restart ``systemd-journald``. The default stays ``200M``. + - >- + system_baseline - ``system_baseline_journal_max_use`` is checked before any change: it must be empty, ``infinity`` or a number followed by + ``K``, ``M``, ``G`` or ``T``. A value in any other form, which the role used to write into the drop-in as it was (a bare number, ``1.5G``, + a typo, a line break), now stops the run; an empty value used to write an empty ``SystemMaxUse=``. diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index 4878c11..99e78e0 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -44,7 +44,7 @@ templating error instead of the role's own message. | `system_baseline_unattended_upgrade_package_blacklist` | `[]` | no | Packages unattended-upgrades must not touch, as regular expressions (see below) | | `system_baseline_sysctl_hardening` | from profile | no | List of `name` and `value` sysctl pairs | | `system_baseline_secure_tmp_mounts` | from profile | no | Paths remounted as tmpfs with `noexec,nosuid,nodev` | -| `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`). | +| `system_baseline_journal_max_use` | `200M` | no | Upper bound of the persistent journal (journald `SystemMaxUse`): a number and `K`, `M`, `G` or `T`, or `infinity`. Empty leaves the host alone and removes nothing a former run wrote (see "Leaving journald alone") | | `system_baseline_tmux_autostart` | `false` | no | Attach interactive SSH logins to a tmux session (`ubuntu_lxc` and `ubuntu_vm` only) | | `system_baseline_tmux_session` | `main` | no | Session name, `A-Za-z0-9_-`, up to 32 characters | | `system_baseline_tmux_windows` | `[]` | no | `{name, command}` windows made when the session is created | @@ -128,12 +128,13 @@ The two task files besides `main` are a supported interface, for a caller that d The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_IMAGE}` (Ubuntu 24.04) and `${MOLECULE_IMAGE_2604}` (Ubuntu 26.04). It installs packages from the Ubuntu mirrors, so the runner needs outbound network. It runs `check` before the converge (a fresh host) and after it (a configured host). -- Converge first checks that the role refuses a bad input with its own message before any change: an unknown `system_baseline_system_type`, an unknown `system_baseline_apt_upgrade` (main flow and `update` entry point), a negative reboot throttle or a negative or boolean post-reboot delay (main flow and `reboot` entry point), a line break in `system_baseline_apt_daily_timeout`, and a bad package blacklist (a quote, a null item, a bare string). +- Converge first checks that the role refuses a bad input with its own message before any change: an unknown `system_baseline_system_type`, an unknown `system_baseline_apt_upgrade` (main flow and `update` entry point), a negative reboot throttle or a negative or boolean post-reboot delay (main flow and `reboot` entry point), a line break in `system_baseline_apt_daily_timeout`, a bad `system_baseline_journal_max_use` (a bare number, a space, a line break, a number), and a bad package blacklist (a quote, a null item, a bare string). - Converge then applies the `ubuntu_lxc` profile, with tmux autostart and `system_baseline_apt_daily_timeout: 1h`, and only resolves the `pve` and `ubuntu_vm` profiles and a consumer override, asserting the resolved inputs. - Verify checks the installed and removed packages, the journal size cap, the apt settings in `20auto-upgrades` and `50unattended-upgrades`, the locale, and that systemd loaded the `apt-daily.service` timeout. - Verify checks the tmux snippet: root-owned, valid shell, the session and quoted window command, no effect without a terminal, a session name or window command ending in a newline refused, and the file removed when autostart is off. - Converge refuses bad items in `system_baseline_extra_packages` and `system_baseline_extra_remove_packages` (whitespace, a null, an empty string, a trailing minus, upper case, a bare string) and a package that one input installs and another purges, then applies the `ubuntu_lxc` profile with `jq` as an extra package and `ed` as an extra removal; verify checks that `jq` is installed, `ed` is gone and the profile's packages are still there, and that an extra `tmux` installs the snippet where a flat list without it installs none. - Converge also checks that a bad `system_baseline_apt_tmpdir` (under `/tmp` or `/var/tmp`, relative, with `..`, empty) is refused in the main flow and in the `update` entry point. Verify reads `tasks/update.yml` and checks that the scratch directory is created with mode `0700`, that both apt tasks set `TMPDIR` to it, and that the connection is reset afterwards: the scenario skips the `update` tag, so the upgrade itself never runs there. +- Verify ends by running the role once with `system_baseline_journal_max_use: ""` after removing the drop-in, and asserts that no drop-in is written and that `systemd-journald` was not restarted. - Verify runs the `reboot` entry point with `system_baseline_reboot_if_required: false`, without and with `/var/run/reboot-required`, and checks the fact and that the host did not reboot. - The `pve` origins pin is applied to the Ubuntu container and read back with `apt-config dump`, then removed again. The package blacklist is written, read back as a list, left alone by a second run and removed by an empty list. @@ -211,6 +212,10 @@ The profile key `apt_upgrade` (`safe` or `dist`, resolved to `system_baseline_ap - The `update` entry point follows the same input: it upgrades with `dist` when `system_baseline_system_type` is `pve`. Without a `system_baseline_system_type` (the entry point does not require one) it stays on `safe`. - Only the apt upgrade changes. Autoremove and autoclean, the check-mode skip and unattended-upgrades are as before; the example blacklist below keeps unattended-upgrades away from the Proxmox packages. +### Leaving journald alone + +`system_baseline_journal_max_use: ""` skips the journald task: no drop-in directory, no `50-system-baseline.conf` and no restart of `systemd-journald`. Use it where another drop-in, role or policy owns the journal size. A file an earlier run wrote stays, as for an empty `system_baseline_apt_daily_timeout`; remove it by hand if the cap should go. A value that is not empty and not a size (`300`, `0`, `10 M`, one with a line break) stops the run before any change, in the same way as the apt-daily value. + ### Apt scratch directory The upgrade runs over the SSH connection Ansible uses. An `openssh-server` upgrade restarts `ssh.service`, and a unit with `PrivateTmp=yes` (the `systemd_hardening` role sets it) has its own `/tmp` and `/var/tmp`, which systemd deletes when the unit stops. The files apt staged there for the running upgrade then disappear and dpkg fails, leaving packages unpacked but not configured. So the `update` flow creates `system_baseline_apt_tmpdir` (root, mode `0700`), runs the upgrade and the autoremove with `TMPDIR` set to it, and opens a new connection afterwards, so that later tasks get a fresh private `/tmp`. diff --git a/roles/system_baseline/defaults/main.yml b/roles/system_baseline/defaults/main.yml index 1a39db4..87a2e49 100644 --- a/roles/system_baseline/defaults/main.yml +++ b/roles/system_baseline/defaults/main.yml @@ -18,7 +18,8 @@ system_baseline_apt_tmpdir: /var/cache/system-baseline-apt-tmp # Run the package update (tasks/update.yml) in the main flow. false skips it, for hosts that are patched by a separate, # operator-run flow; the tasks_from: update entry point does not read it. system_baseline_update: true -# Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it. +# Upper bound of the persistent journal (journald SystemMaxUse); older archived files are removed above it. Empty leaves the host alone +# (tasks/journald.yml is not run; a drop-in an earlier run wrote stays). system_baseline_journal_max_use: 200M # Attach an interactive SSH login to a tmux session (see tasks/tmux.yml). Off by default: it changes what every login does. # Installed only when tmux is among the packages to install: the ubuntu_lxc and ubuntu_vm profiles have it, the pve profile has none unless diff --git a/roles/system_baseline/meta/argument_specs.yml b/roles/system_baseline/meta/argument_specs.yml index 9f0e417..04ba64f 100644 --- a/roles/system_baseline/meta/argument_specs.yml +++ b/roles/system_baseline/meta/argument_specs.yml @@ -55,6 +55,10 @@ argument_specs: description: - Upper bound of the persistent systemd journal (journald C(SystemMaxUse), for example C(200M)). - Written to a drop-in under C(/etc/systemd/journald.conf.d). + - >- + A number and one of C(K), C(M), C(G), C(T), or C(infinity); anything else (a bare number, a space, a line break) is refused + before any change. Empty leaves the host alone: no drop-in is written and journald is not restarted. + Clearing the value later does not remove a file already written. system_baseline_tmux_autostart: type: bool default: false diff --git a/roles/system_baseline/molecule/default/converge.yml b/roles/system_baseline/molecule/default/converge.yml index 0a0b4d8..11bb7b4 100644 --- a/roles/system_baseline/molecule/default/converge.yml +++ b/roles/system_baseline/molecule/default/converge.yml @@ -118,6 +118,24 @@ that: "'system_baseline_apt_daily_timeout must be' in ansible_failed_result.msg | default('')" quiet: true +# The journal cap is a number and a unit letter, or empty: a bare number (journald would read bytes), a zero, a space, a line break, a +# lower-case unit and a number that is not a string each stop the run before any change. +- name: A bad journal size cap is refused + hosts: all + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_journal_max_use.yml + vars: + system_baseline_refused_journal: "{{ item }}" + loop: + - "300" + - "0" + - 10 M + - "10m" + - "200M\nStorage=none" + - 300 + # A quote, a null item and a bare string (not a list) each stop the run: the bare string would otherwise be split into one-character # patterns, and the null item would become an empty pattern that matches every package. - name: A bad package blacklist is refused diff --git a/roles/system_baseline/molecule/default/tasks/refuse_journal_max_use.yml b/roles/system_baseline/molecule/default/tasks/refuse_journal_max_use.yml new file mode 100644 index 0000000..c0b421a --- /dev/null +++ b/roles/system_baseline/molecule/default/tasks/refuse_journal_max_use.yml @@ -0,0 +1,18 @@ +--- +# One refusal: the role must stop on validation, before it changes anything, with a message that names the variable. +- name: Run the role with a bad system_baseline_journal_max_use + block: + - name: Include system_baseline + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_journal_max_use: "{{ system_baseline_refused_journal }}" + - name: Unreachable when validation works + ansible.builtin.fail: + msg: system_baseline ran with an invalid system_baseline_journal_max_use + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: "'system_baseline_journal_max_use must be' in ansible_failed_result.msg | default('')" + quiet: true diff --git a/roles/system_baseline/molecule/default/verify.yml b/roles/system_baseline/molecule/default/verify.yml index bc0dca2..7afc4b2 100644 --- a/roles/system_baseline/molecule/default/verify.yml +++ b/roles/system_baseline/molecule/default/verify.yml @@ -450,3 +450,48 @@ - system_baseline_verify_blacklist_dump_removed.stdout_lines | select('match', 'Unattended-Upgrade::Package-Blacklist::\s') | list == [] quiet: true tags: always + +# An empty system_baseline_journal_max_use leaves journald alone: with the drop-in gone, the role neither writes it again nor restarts +# systemd-journald. It runs last, because it applies the role with its defaults (the converge's tmux autostart and apt-daily timeout are +# not set here) and the checks above read what the converge wrote. +# It removes what the converge wrote, so a second `molecule verify` needs a converge first. +- name: An empty journal size cap leaves journald alone + hosts: all + gather_facts: true + tasks: + - name: Remove the drop-in and its directory + ansible.builtin.file: + path: /etc/systemd/journald.conf.d + state: absent + + - name: Note when journald last started + ansible.builtin.command: + argv: [systemctl, show, systemd-journald, --property=ActiveEnterTimestampMonotonic, --value] + register: system_baseline_verify_journald_before + changed_when: false + + - name: Run the role with an empty cap + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_journal_max_use: "" + + - name: Look for the drop-in directory + ansible.builtin.stat: + path: /etc/systemd/journald.conf.d + register: system_baseline_verify_journald_dir + + - name: Note when journald last started, after the run + ansible.builtin.command: + argv: [systemctl, show, systemd-journald, --property=ActiveEnterTimestampMonotonic, --value] + register: system_baseline_verify_journald_after + changed_when: false + + - name: Nothing was written and journald was not restarted + ansible.builtin.assert: + that: + - not system_baseline_verify_journald_dir.stat.exists + - system_baseline_verify_journald_before.stdout | length > 0 + - system_baseline_verify_journald_after.stdout == system_baseline_verify_journald_before.stdout + quiet: true diff --git a/roles/system_baseline/tasks/main.yml b/roles/system_baseline/tasks/main.yml index 0917c46..0745c00 100644 --- a/roles/system_baseline/tasks/main.yml +++ b/roles/system_baseline/tasks/main.yml @@ -30,6 +30,7 @@ - name: Cap the journal size ansible.builtin.import_tasks: journald.yml + when: system_baseline_journal_max_use | length > 0 tags: journald - name: Bound a hung apt-daily.service diff --git a/roles/system_baseline/tasks/validate.yml b/roles/system_baseline/tasks/validate.yml index b9d054b..ac4d754 100644 --- a/roles/system_baseline/tasks/validate.yml +++ b/roles/system_baseline/tasks/validate.yml @@ -47,6 +47,19 @@ ansible.builtin.import_tasks: validate_reboot.yml tags: always +# The value is written into a journald drop-in: a number and a unit letter, so a bare number (journald reads it as bytes), a space or a line +# break (a second directive) never reaches the file. Empty leaves the host alone, as for the apt-daily timeout. +- name: Validate the journal size cap + ansible.builtin.assert: + that: + - system_baseline_journal_max_use is string + - system_baseline_journal_max_use == '' or system_baseline_journal_max_use is match('^(infinity|[0-9]+[KMGT])\Z') + fail_msg: >- + system_baseline_journal_max_use must be empty (leave journald alone), infinity or a size such as 200M or 2G + (a number and one of K, M, G, T; a bare number is refused, journald would read it as bytes). + quiet: true + tags: always + # The value is written into a unit file: one line, starting with a digit, so no line break can add a second directive. systemd itself # refuses a value it cannot parse (it ignores the setting and logs it). - name: Validate the apt-daily start timeout From 19449f7e93b95c550fe4a0ce474465e51c875555 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 27 Nov 2026 07:50:27 +0000 Subject: [PATCH 11/26] chore(deps): update ubuntu:24.04 docker digest to 562111b --- images/molecule-ubuntu2404/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/images/molecule-ubuntu2404/Dockerfile b/images/molecule-ubuntu2404/Dockerfile index 4161b44..3946f10 100644 --- a/images/molecule-ubuntu2404/Dockerfile +++ b/images/molecule-ubuntu2404/Dockerfile @@ -25,7 +25,7 @@ # fails without host keys, so they cannot be removed; image scanners will flag them. # They are throwaway keys of a test target that is never exposed. # ubuntu:24.04 index digest as of 2026-10-24 (24.04.5). -FROM ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289 +FROM ubuntu:24.04@sha256:562111b88caa79c71391c0c4d3c2114a7d5c35915c20561fd893cb1e07929e6b LABEL org.opencontainers.image.title="molecule-ubuntu2404" \ org.opencontainers.image.description="Disposable Ubuntu 24.04 test target for the molecule scenarios of the mortis.kamino Ansible Collection. systemd runs as PID 1 with D-Bus, sudo, python3 and the packages the roles manage (iptables, ufw, fail2ban, openssh-server) preinstalled, so a converge makes no network calls. Start it as a molecule platform (usage label); it carries throwaway SSH host keys and is a test target only, never to be exposed." \ From 2e92b11cbccd57a7d70c0254c74bf13fec7b381d Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 08:15:18 +0000 Subject: [PATCH 12/26] remove image.yml timeout --- .gitea/workflows/image.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitea/workflows/image.yml b/.gitea/workflows/image.yml index 07ab4a3..7e212c9 100644 --- a/.gitea/workflows/image.yml +++ b/.gitea/workflows/image.yml @@ -62,7 +62,6 @@ jobs: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: kamino-docker - timeout-minutes: 45 # max-parallel: 1 keeps the builds to one at a time. The runner takes two jobs, so a build # may share it with one other job (Lint, Build or Molecule). An empty subpath means the # repository root is the build context. From e2df672be72f04a276dd19701cc4bbaf7b9c14a2 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 08:15:45 +0000 Subject: [PATCH 13/26] remove molecule.yml timeout --- .gitea/workflows/molecule.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.gitea/workflows/molecule.yml b/.gitea/workflows/molecule.yml index ced0649..252742b 100644 --- a/.gitea/workflows/molecule.yml +++ b/.gitea/workflows/molecule.yml @@ -47,10 +47,6 @@ jobs: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) runs-on: [kamino-molecule] - # Two full runs sharing the runner (a nightly run and a dispatch) take more than 30 minutes. - # Also the age past which the sweep step removes a run's containers; a script test holds the - # two equal. - timeout-minutes: 45 env: # The tools and collections molecule runs with: the image Lint and Build use. CI_IMAGE: >- From 18475ea0a50a1a8cd3d1e1d7106f061e97a4a800 Mon Sep 17 00:00:00 2001 From: Dragonish Date: Fri, 27 Nov 2026 08:47:25 +0000 Subject: [PATCH 14/26] fix(ci): give the molecule job a 90 minute timeout Removing timeout-minutes left the sweep step's 45 minute bound without the job timeout it must equal, and the script test that holds the two equal failed with a KeyError. Restore the key at 90 minutes, which also leaves a full run under load (PR #405 took 44m53s) real margin, and move the sweep bound to match so a live run's containers are never removed. Assisted-by: Claude Code --- .gitea/workflows/molecule.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/molecule.yml b/.gitea/workflows/molecule.yml index 252742b..6358ab5 100644 --- a/.gitea/workflows/molecule.yml +++ b/.gitea/workflows/molecule.yml @@ -47,6 +47,9 @@ jobs: (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) runs-on: [kamino-molecule] + # A full run under load takes about 45 minutes (PR #405: 44m53s), so 45 left no margin. Also the + # age past which the sweep step removes a run's containers; a script test holds the two equal. + timeout-minutes: 90 env: # The tools and collections molecule runs with: the image Lint and Build use. CI_IMAGE: >- @@ -94,7 +97,7 @@ jobs: ids="$(docker ps -aq --filter 'label=net.rkdr.mortis.molecule-run')" # The job's timeout-minutes (a script test holds them equal): a shorter bound would remove a # live run's containers. - cutoff="$(date -d '45 minutes ago' +%s)" + cutoff="$(date -d '90 minutes ago' +%s)" old="" for id in $ids; do # a container removed since the listing, by its run or another run's sweep, is skipped From 2d4d44b8716eb48b133a2ae6ded35e3c6e22ef6f Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 27 Nov 2026 11:27:28 +0000 Subject: [PATCH 15/26] chore(deps): update ubuntu:24.04 docker digest to 562111b --- .gitea/workflows/image.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/image.yml b/.gitea/workflows/image.yml index 7e212c9..1740816 100644 --- a/.gitea/workflows/image.yml +++ b/.gitea/workflows/image.yml @@ -79,7 +79,7 @@ jobs: base: "0.1" subpath: images/molecule-ubuntu2404 dockerfile: Dockerfile - job_image: ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289 + job_image: ubuntu:24.04@sha256:562111b88caa79c71391c0c4d3c2114a7d5c35915c20561fd893cb1e07929e6b - name: molecule-ubuntu2604 base: "0.1" subpath: images/molecule-ubuntu2604 From 7433a376972c6ad0417693937ff1838a2201e098 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 27 Nov 2026 11:39:00 +0000 Subject: [PATCH 16/26] chore(deps): update dependency community.docker to v5.4.1 --- extensions/molecule/requirements.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/molecule/requirements.yml b/extensions/molecule/requirements.yml index 5f967f9..02597c2 100644 --- a/extensions/molecule/requirements.yml +++ b/extensions/molecule/requirements.yml @@ -7,4 +7,4 @@ # Renovate (renovate.json, ansible-galaxy manager) bumps this pin. collections: - name: community.docker - version: 5.4.0 + version: 5.4.1 From 042051b3e56662d23ee6220a779e8bc1ac9d7d76 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 27 Nov 2026 13:02:52 +0000 Subject: [PATCH 17/26] chore(deps): update git.rkdr.net/mortis/ci docker tag to v0.2.48 --- .gitea/workflows/build.yml | 2 +- .gitea/workflows/gitea-release-key.yml | 2 +- .gitea/workflows/lint.yml | 2 +- .gitea/workflows/molecule.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 3ac55be..d49b4a9 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -28,7 +28,7 @@ jobs: timeout-minutes: 30 # The ci image (images/ci, built by image.yml): tag for the release, digest enforced. container: - image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc + image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d env: PIP_DISABLE_PIP_VERSION_CHECK: "1" steps: diff --git a/.gitea/workflows/gitea-release-key.yml b/.gitea/workflows/gitea-release-key.yml index 0e50ffe..ea44cc6 100644 --- a/.gitea/workflows/gitea-release-key.yml +++ b/.gitea/workflows/gitea-release-key.yml @@ -44,7 +44,7 @@ jobs: # The ci image (images/ci, built by image.yml), at the pin of lint.yml: tag for the # release, digest enforced. Only its /opt/venv Python (with PyYAML) is used here. container: - image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc + image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d steps: # The container has no Node, so JavaScript actions such as actions/checkout # cannot run; clone with git and the job token. diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index a069946..c88fae1 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -31,7 +31,7 @@ jobs: # The tag says which release, the digest is what is enforced (bump both together # when image.yml publishes a new version). container: - image: git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc + image: git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d env: PIP_DISABLE_PIP_VERSION_CHECK: "1" PRE_COMMIT_HOME: /opt/pre-commit diff --git a/.gitea/workflows/molecule.yml b/.gitea/workflows/molecule.yml index 6358ab5..b77804e 100644 --- a/.gitea/workflows/molecule.yml +++ b/.gitea/workflows/molecule.yml @@ -53,7 +53,7 @@ jobs: env: # The tools and collections molecule runs with: the image Lint and Build use. CI_IMAGE: >- - git.rkdr.net/mortis/ci:0.2.46@sha256:a03015cc2177bdd6ef7f348f245a89f361893c7c64edc1264d9f9c1387d9defc + git.rkdr.net/mortis/ci:0.2.48@sha256:d1c6653255abf366462c0265d9372626d5b59095084fe74ae95b9ebe7414007d # Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run # one locally. MOLECULE_IMAGE: >- From 3d2fab53886188cca4851eadfa34c2202071a166 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 13:37:49 +0000 Subject: [PATCH 18/26] docs: update a branch from main only when it is next to merge main blocks an outdated branch, so every update re-runs Lint, Build and Molecule and cancels the run in progress. Limit updates to the pull request that is next to merge, schedule its merge afterwards, and leave renovate/ branches to Renovate's own rebase. Assisted-by: Claude Code:claude-opus-5-5 --- docs/contributing/making-a-change.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/contributing/making-a-change.md b/docs/contributing/making-a-change.md index 3772e0d..4849e4b 100644 --- a/docs/contributing/making-a-change.md +++ b/docs/contributing/making-a-change.md @@ -15,10 +15,19 @@ trailers, are in [ai-assistance.md](ai-assistance.md). *Reason:* every change reaches `main` through the Lint and Build checks and a reviewer. *Held by:* control: branch protection on `main`. - **Do not push to someone else's branch or to a bot's branch; put your change in a pull request of - your own.** Updating a branch from `main` with Gitea's update button is allowed. + your own.** Updating a branch from `main` with Gitea's update button is allowed under the next + rule. *Reason:* a push changes a head its author already reviewed or scheduled to merge, and a hand-made commit on a `renovate/` branch makes Renovate stop rebasing it. *Held by:* aspirational. +- **Update a pull request's branch from `main` only when it is next to merge: reviewed, green on its + previous head, and the only branch being updated. After updating your own pull request, give it a + scheduled merge; merge anyone else's as [reviewing.md](reviewing.md) says. Never update a + `renovate/` branch: Renovate rebases its branches that fall behind `main` at its next run.** + *Reason:* `main` blocks an outdated branch, so every update re-runs Lint, Build and Molecule, and + a new head cancels the run in progress; an update made while another pull request merges first is + wasted. + *Held by:* aspirational. - **File an issue or open a pull request with the headings of the matching template in `.gitea/`, also when you file through the API, `tea` or an MCP server.** *Reason:* those routes skip the templates, and an agent's built-in body leaves out what review needs. From bf604a1af2f0c2e5adbb2391a01bb5aac4e8b9c0 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 13:38:09 +0000 Subject: [PATCH 19/26] docs(adr): run Molecule in its own controller image Record ADR 0003: Molecule runs in a molecule-controller image that bakes only Molecule's tools, from a requirements file and hash-pinned lock of its own, so a ci pin pull request no longer moves molecule.yml and runs no scenario. The ADR lists the files the implementation updates and the alternatives not taken. Assisted-by: Claude Code:claude-opus-5-5 --- docs/adr/0003-molecule-controller-image.md | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 docs/adr/0003-molecule-controller-image.md diff --git a/docs/adr/0003-molecule-controller-image.md b/docs/adr/0003-molecule-controller-image.md new file mode 100644 index 0000000..47c451b --- /dev/null +++ b/docs/adr/0003-molecule-controller-image.md @@ -0,0 +1,59 @@ +# 0003. Molecule runs in its own controller image, not the `ci` image + +Status: accepted + +## Context + +[ADR 0002](0002-self-built-ci-and-molecule-images.md) built one `ci` image that bakes every CI +tool, and Lint, Build and Molecule all pin it. A change to a tool only Lint uses (apm-cli, +antsibull-changelog, a pre-commit hook environment) publishes a new `ci` version, and its pin +pull request moves `CI_IMAGE` in `molecule.yml`. The scenario selector cannot tell what changed +inside an image, so it runs every scenario. About half of the `ci` pin pull requests were +Lint-only. Images are built only on push to `main`, so a bump and its pin never share a pull +request. + +## Decision + +- **Molecule runs in a `molecule-controller` image**, separate from `ci`. It bakes only what + Molecule needs: ansible-core, molecule, molecule-plugins, the Python packages of the Docker + connection, and the collections of `requirements.yml` and + `extensions/molecule/requirements.yml`. +- **Its Python packages come from a requirements file and hash-pinned lock of its own.** +- **`molecule.yml` pins it instead of `ci`**; Lint and Build keep `ci`. +- **It follows ADR 0002 otherwise:** built by `image.yml`, versioned by CI, pinned by + `@sha256:`, moved by Renovate. This adds to ADR 0002's set of images; the + rest of ADR 0002 stands. + +## Reason + +A `ci` pin pull request then touches only paths the selector ignores and runs no scenario. A +`molecule-controller` pin pull request still runs every scenario, which is right: it changes +Molecule's tools. + +The cost: one more image and lock to maintain, its layers to estimate against the 100 MB limit, +a hand-made first pin, and ansible-core pinned in two locks that must stay equal. A collection +bump is an input of both images, so it publishes two versions and two pin pull requests. + +The controller's requirements file and lock must not be on the selector's IGNORED list, so a +bump of ansible-core or molecule there runs every scenario before it merges. Today +`requirements-dev.txt` and `requirements-dev.lock` are on IGNORED, so such a bump selects no +scenario unless it edits `meta/runtime.yml`; this decision does not change that list. + +The implementation updates: `image.yml` (matrix), `molecule.yml`, +`scripts/run_molecule_in_ci_image.sh` (its pin comparison reads the `ci` image's checksums), +`scripts/check_image_versions.py`, `scripts/check_bot_pr_diff.py` and +`scripts/lock-requirements.sh` (they know only `requirements-dev.lock`), their tests, the +`pip-compile` patterns in `renovate.json`, `images/AGENTS.md` (the consumer list, and "each +molecule image is one Ubuntu release"), the Molecule rules in `.gitea/workflows/AGENTS.md`, +`docs/images/` (a new page, and `ci.md`, which names Molecule as a consumer), the `ci` +Dockerfile's description label, `docs/contributing/setup.md` if the clone's tools change, and the +[Accepted risks](../../SECURITY.md#accepted-risks) entry "Pin bumps first behaviour-tested after +they merge", which counts on the `ci` pin pull request running every scenario. + +## Not done + +- **The selector classifies the packages a lock change moves, to decide whether a `CI_IMAGE` + bump matters:** a heuristic package list inside a script that judges pull requests. +- **Status quo:** every Lint-only tool change keeps costing a full Molecule run. +- **Grouping pin pull requests only:** adopted separately; it lowers the number of full runs + but not the cause. From 699179674fdbad1d056daaa8ba40e28aa7de00f6 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 13:45:55 +0000 Subject: [PATCH 20/26] docs: bring a renovate/ branch up to date through its rebase checkbox A Renovate pull request is not always rebased just for falling behind main, so forbidding every update would leave it stuck. Never use the update button on it; tick the rebase/retry checkbox instead, and say why a hand-made update commit is excluded. Assisted-by: Claude Code:claude-opus-5-5 --- docs/contributing/making-a-change.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/contributing/making-a-change.md b/docs/contributing/making-a-change.md index 4849e4b..fc74cbc 100644 --- a/docs/contributing/making-a-change.md +++ b/docs/contributing/making-a-change.md @@ -16,18 +16,22 @@ trailers, are in [ai-assistance.md](ai-assistance.md). *Held by:* control: branch protection on `main`. - **Do not push to someone else's branch or to a bot's branch; put your change in a pull request of your own.** Updating a branch from `main` with Gitea's update button is allowed under the next - rule. + two rules. *Reason:* a push changes a head its author already reviewed or scheduled to merge, and a hand-made commit on a `renovate/` branch makes Renovate stop rebasing it. *Held by:* aspirational. - **Update a pull request's branch from `main` only when it is next to merge: reviewed, green on its previous head, and the only branch being updated. After updating your own pull request, give it a - scheduled merge; merge anyone else's as [reviewing.md](reviewing.md) says. Never update a - `renovate/` branch: Renovate rebases its branches that fall behind `main` at its next run.** + scheduled merge; merge anyone else's as [reviewing.md](reviewing.md) says.** *Reason:* `main` blocks an outdated branch, so every update re-runs Lint, Build and Molecule, and a new head cancels the run in progress; an update made while another pull request merges first is wasted. *Held by:* aspirational. +- **Never press the update button on a `renovate/` branch. When a Renovate pull request is next to + merge and behind `main`, tick the rebase/retry checkbox in its description; Renovate rebases it at + its next run.** + *Reason:* the update button adds a hand-made commit, and Renovate stops rebasing that branch. + *Held by:* aspirational. - **File an issue or open a pull request with the headings of the matching template in `.gitea/`, also when you file through the API, `tea` or an MCP server.** *Reason:* those routes skip the templates, and an agent's built-in body leaves out what review needs. From 04259751ad176257217da7e706cb00f446cfa67a Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 13:50:55 +0000 Subject: [PATCH 21/26] docs(adr): point ADR 0002 to ADR 0003 and sharpen 0003 ADR 0002's image bullet now names ADR 0003 as the decision that adds Molecule's controller image; its decision is unchanged. ADR 0003 states the Lint-only share of ci pin pull requests as a count and lists the push paths of image.yml among the files the implementation updates. Assisted-by: Claude Code:claude-opus-5-5 --- docs/adr/0002-self-built-ci-and-molecule-images.md | 1 + docs/adr/0003-molecule-controller-image.md | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/adr/0002-self-built-ci-and-molecule-images.md b/docs/adr/0002-self-built-ci-and-molecule-images.md index f208c4a..3e58423 100644 --- a/docs/adr/0002-self-built-ci-and-molecule-images.md +++ b/docs/adr/0002-self-built-ci-and-molecule-images.md @@ -12,6 +12,7 @@ and pin updates. The choice is hard to undo once every workflow pins an image. - **We build our own images:** a `ci` image, and one Dockerfile per molecule image (one per Ubuntu release, and later the Debian 13 one). + Molecule's controller image is added by [ADR 0003](0003-molecule-controller-image.md). - **The molecule images bake in everything except what a role installs itself.** The test fixtures a scenario's `prepare.yml` needs are baked in. Packages a role installs are still downloaded, because that install path is what the test exercises. A converge is not kept off diff --git a/docs/adr/0003-molecule-controller-image.md b/docs/adr/0003-molecule-controller-image.md index 47c451b..dc39877 100644 --- a/docs/adr/0003-molecule-controller-image.md +++ b/docs/adr/0003-molecule-controller-image.md @@ -8,8 +8,8 @@ Status: accepted tool, and Lint, Build and Molecule all pin it. A change to a tool only Lint uses (apm-cli, antsibull-changelog, a pre-commit hook environment) publishes a new `ci` version, and its pin pull request moves `CI_IMAGE` in `molecule.yml`. The scenario selector cannot tell what changed -inside an image, so it runs every scenario. About half of the `ci` pin pull requests were -Lint-only. Images are built only on push to `main`, so a bump and its pin never share a pull +inside an image, so it runs every scenario. 9 of 18 `ci` pin pull requests over two weeks +were Lint-only. Images are built only on push to `main`, so a bump and its pin never share a pull request. ## Decision @@ -39,7 +39,8 @@ bump of ansible-core or molecule there runs every scenario before it merges. Tod `requirements-dev.txt` and `requirements-dev.lock` are on IGNORED, so such a bump selects no scenario unless it edits `meta/runtime.yml`; this decision does not change that list. -The implementation updates: `image.yml` (matrix), `molecule.yml`, +The implementation updates: `image.yml` (matrix, and its push `paths` unless the new files live +under `images/`), `molecule.yml`, `scripts/run_molecule_in_ci_image.sh` (its pin comparison reads the `ci` image's checksums), `scripts/check_image_versions.py`, `scripts/check_bot_pr_diff.py` and `scripts/lock-requirements.sh` (they know only `requirements-dev.lock`), their tests, the From 16b1aa4136fa9865f1c69ab6c338d0857ea40b78 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 14:25:23 +0000 Subject: [PATCH 22/26] ci(renovate): group updates and open them on Mondays Updates, lock file maintenance included, open on Mondays (UTC) so any Monday run can act, with no hourly pull request limit; the weekly window and the groups bound the volume. Groups: own CI images (ci and both molecule pins, exempt from the schedule), ubuntu base images (Dockerfile FROM and image.yml job_image digests in one branch, so manual), lint tooling and pre-commit hooks. osvVulnerabilityAlerts brings fixes from osv.dev; they skip the schedule and the release-age wait, so vulnerabilityAlerts.automerge false keeps a person on each one. Assisted-by: Claude Code:claude-opus-5-5 --- renovate.json | 57 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/renovate.json b/renovate.json index 6193547..702af45 100644 --- a/renovate.json +++ b/renovate.json @@ -1,6 +1,6 @@ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit.", + "description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit. Updates open on Mondays (UTC), so any Monday run can act; the own image pins and vulnerability fixes found on osv.dev open at any time. The weekly window and the groups bound the volume, so there is no hourly pull request limit. Vulnerability fixes skip the release-age wait, so they are never automerged: a person checks a fix that had no time to be pulled as a compromised release. Base-image bumps are manual: every Dockerfile is FROM ubuntu, grouped with the job containers.", "extends": [ "config:recommended", ":enablePreCommit" @@ -19,7 +19,7 @@ ], "automerge": true, "automergeType": "pr", - "prHourlyLimit": 5, + "prHourlyLimit": 0, "minimumReleaseAge": "3 days", "minimumReleaseAgeBehaviour": "timestamp-optional", "timezone": "UTC", @@ -90,7 +90,7 @@ ], "packageRules": [ { - "description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The merge publishes a new image version.", + "description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The merge publishes a new image version. Today every Dockerfile is FROM ubuntu, whose bumps join the manual ubuntu base images group below; this rule is the safety net for a future base image of another kind.", "matchManagers": [ "dockerfile" ], @@ -145,12 +145,18 @@ "allowedVersions": "<=26.10.1" }, { - "description": "The job containers of image.yml (matrix job_image, ubuntu by digest) hold the org registry push credential while the image job runs: never automerged, and kept in their own branch so the Dockerfile base-image bumps are not held back with them.", + "description": "The job containers of image.yml (matrix job_image, ubuntu by digest) hold the org registry push credential while the image job runs: never automerged. Their ubuntu bumps share one branch with the Dockerfile FROM bumps (ubuntu base images rule below), so that pull request is manual too: a group automerges only if every update in it does.", "matchFileNames": [ ".gitea/workflows/image.yml" ], - "automerge": false, - "additionalBranchPrefix": "job-container-" + "automerge": false + }, + { + "description": "The Dockerfile FROM digests and the image.yml job_image digests of one Ubuntu update move in one pull request, so the release pair stays in step and one Images run covers both.", + "matchPackageNames": [ + "ubuntu" + ], + "groupName": "ubuntu base images" }, { "description": "Safety net only: kaniko is pinned by layer digests in image.yml and no Renovate manager reads them, so it is updated by hand. If a manager ever starts to read it, its bumps are not automerged.", @@ -160,11 +166,15 @@ "automerge": false }, { - "description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:@sha256: pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).", + "description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:@sha256: pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above). One pull request moves every image an Images run published (ci and both molecule images), so one Molecule run tests them together. Exempt from the weekly schedule, so the pins on main catch up with a new image within minutes.", "matchPackageNames": [ "git.rkdr.net/mortis/**" ], - "automerge": true + "automerge": true, + "groupName": "own CI images", + "schedule": [ + "at any time" + ] }, { "description": "Look the pre-commit hook repositories up with git ls-remote (git-tags) instead of the GitHub API. This run has no GitHub token, and the github-tags datasource then either skips every hook (skipReason github-token-required, dry run 3880) or is refused at once with 403 rate limit (githubTokenWarn off, local run). git-tags needs no API and no credential, and it uses the dereferenced hash of an annotated tag, so the new rev is the commit, as pre-commit needs. The `# frozen:` form is kept by the manager's own replace template. It works only together with RENOVATE_GITHUB_TOKEN_WARN=false in renovate.yml: the token check runs after extraction and skips every github-tags dependency before a package rule can change its datasource (local run, Renovate 44.161.0). git-tags has no release timestamps, so minimumReleaseAge cannot delay a hook bump: hook bumps are never automerged, a person reviews each one.", @@ -177,16 +187,45 @@ "overrideDatasource": "git-tags", "overridePackageName": "https://github.com/{{{depName}}}", "automerge": false + }, + { + "description": "Lint and build tooling in one weekly pull request across requirements-dev.lock and the ci image's uv pin, so one ci image build instead of one per tool.", + "matchDatasources": [ + "pypi" + ], + "matchPackageNames": [ + "apm-cli", + "antsibull-changelog", + "galaxy-importer", + "reuse", + "pre-commit", + "uv" + ], + "groupName": "lint tooling" + }, + { + "description": "The pre-commit hooks in one weekly pull request; never automerged (rule above).", + "matchManagers": [ + "pre-commit" + ], + "groupName": "pre-commit hooks" } ], "lockFileMaintenance": { "enabled": true, "schedule": [ - "before 6am on monday" + "on monday" ], "automerge": false, "labels": [ "lock-file-maintenance" ] + }, + "schedule": [ + "on monday" + ], + "osvVulnerabilityAlerts": true, + "vulnerabilityAlerts": { + "automerge": false } } From 6eca2f4031d8711cc1533c860a7bbb2047d2169c Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 14:36:24 +0000 Subject: [PATCH 23/26] ci(molecule): select by image pin for a molecule.yml change of only pins or comments A change to .gitea/workflows/molecule.yml selected every scenario, so a molecule image pin bump or a comment edit ran the full set. The selector now compares the merge-base and HEAD copies of the workflow: - `#` and blank lines outside a block scalar are dropped; inside one (a `run: |` script, where they may be heredoc content) they count; - the line after each CI_IMAGE, MOLECULE_IMAGE and MOLECULE_IMAGE_2604 `>-` key must be its value, deeper than the key and in the shape Renovate writes, in both copies; - comments only select nothing; a MOLECULE_IMAGE* pin selects every scenario with a file naming it, or every scenario when a shared molecule file names it or a file is unreadable or a symlink; - CI_IMAGE, any other difference or a git error selects everything. reason_for() is split out of select() to stay under ruff's complexity limit. The Molecule rule in .gitea/workflows/AGENTS.md describes the new case. Assisted-by: Claude Code:claude-opus-5-5 --- .gitea/workflows/AGENTS.md | 5 +- scripts/select_molecule_scenarios.py | 179 ++++++++++++-- .../scripts/test_select_molecule_scenarios.py | 232 ++++++++++++++++++ 3 files changed, 395 insertions(+), 21 deletions(-) diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 9250962..3fd006e 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -80,7 +80,10 @@ issue. - **What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`:** the scenarios of the roles it changes and of the roles that use them (any file naming `mortis.kamino.`, transitively), none for a diff of only IGNORED paths, a failure for a - changed role with no scenario, and every scenario for any other file. *Why:* a full run takes + changed role with no scenario, for a `.gitea/workflows/molecule.yml` diff of only comments + (outside `run:` scripts) or image pins the scenarios that name a changed `MOLECULE_IMAGE*` pin + (every scenario for `CI_IMAGE`, or when a shared molecule file names the pin), and every + scenario for any other file. *Why:* a full run takes the single runner slot for a long time. *Held:* control: the selector and its tests. - **A role named in an include, import, play `roles:` entry or meta dependency is written out in full**, never bare or templated. *Why:* the selector finds dependent roles by their FQCN. diff --git a/scripts/select_molecule_scenarios.py b/scripts/select_molecule_scenarios.py index 3ef5560..1562d13 100644 --- a/scripts/select_molecule_scenarios.py +++ b/scripts/select_molecule_scenarios.py @@ -18,6 +18,11 @@ Only a pull request is narrowed, and only when is given and EVENT_NAM extensions/molecule/requirements.yml is "any other file"; * a file on the IGNORED list (documentation, changelog, repository tooling that no scenario reads; galaxy.yml by a rule in .gitea/workflows/AGENTS.md) selects nothing; + * .gitea/workflows/molecule.yml, when only comments, blank lines (both outside a block + scalar such as `run: |`) or the image pins changed: nothing for comments; for + MOLECULE_IMAGE or MOLECULE_IMAGE_2604, every scenario whose directory names that variable, + or every scenario when a shared molecule file names it; for CI_IMAGE (the tools molecule + runs with), every scenario. Any other change to it is "any other file"; * any other file selects every scenario. A role uses another when any file under its directory names it as `mortis.kamino.` @@ -50,6 +55,7 @@ control characters in paths escaped so a crafted file name cannot inject a log c """ import fnmatch +import glob import os import re import subprocess @@ -111,6 +117,21 @@ IGNORED = ( ) +WORKFLOW = ".gitea/workflows/molecule.yml" +# The image pins of WORKFLOW, each a `KEY: >-` line followed by its value line, in the shape +# Renovate writes. +PIN_KEY = re.compile(r"(\s+)(CI_IMAGE|MOLECULE_IMAGE|MOLECULE_IMAGE_2604): >-") +PIN_VALUE = re.compile( + r"(\s+)git\.rkdr\.net/mortis/[a-z0-9._-]+:[^@\s]+@sha256:[0-9a-f]{64}" +) +# A line that opens a block scalar (`run: |`, `if: >-`, `- |`): its `#` lines are content. +# A tagged or anchored opener (`!!str |`, `&a |`) or a bare `|` line is not recognised; adding +# one changes a significant line, so it fails closed. +BLOCK_OPENER = re.compile(r"(\s*).*[:-][ \t]+[|>][-+0-9]*([ \t]+#.*)?") +# Where molecule reads files shared by scenarios; a scenario directory below them is not shared. +SHARED = (".config/molecule", "extensions/molecule", "roles/*/molecule") + + def printable(text): """`text` with control characters (a newline in a file name) escaped, for a log line.""" return "".join( @@ -187,20 +208,134 @@ def with_users(roles, used_by): return found +def _significant(text): + """WORKFLOW's lines without comments and blank lines, and its pins; None when unsure. + + Only lines outside a block scalar are dropped: inside one (a `run: |` script) a `#` line + is content. A pin's value must be the very next line, deeper than its key, in PIN_VALUE's + shape. + """ + lines, pins, key, block = [], [], None, None + for line in text.splitlines(): + indent = len(line) - len(line.lstrip()) + if key: + if not PIN_VALUE.fullmatch(line) or indent <= key[1]: + return None + pins.append((key[0], line.strip())) + lines.append("") + key = None + continue + if block is not None and (not line.strip() or indent > block): + lines.append(line) + continue + block = None + if not line.strip() or line.lstrip().startswith("#"): + continue + match = PIN_KEY.fullmatch(line) + if match: + key = (match[2], len(match[1])) + if BLOCK_OPENER.fullmatch(line): + block = indent + lines.append(line) + return None if key else (lines, pins) + + +def pin_changes(old, new): + """The pins that differ between two texts of WORKFLOW, or None when anything else does. + + An empty set means only comments or blank lines outside block scalars changed. + """ + old_split, new_split = _significant(old), _significant(new) + if old_split is None or new_split is None or old_split[0] != new_split[0]: + return None + return {k for (k, a), (_k, b) in zip(old_split[1], new_split[1]) if a != b} + + +def _raise(error): + raise error + + +def _names(path, word, skip=()): + """Whether a file under `path`, outside the directories in `skip`, matches `word`. + + Raises OSError when a directory or file cannot be read, or is a symlink (os.walk does + not follow one, so what it points to would go unread). + """ + if os.path.islink(path): + raise OSError(f"symlink: {path}") + for dirpath, dirs, files in os.walk(path, onerror=_raise): + for name in dirs + files: + if os.path.islink(os.path.join(dirpath, name)): + raise OSError(f"symlink: {os.path.join(dirpath, name)}") + dirs[:] = [d for d in dirs if os.path.join(dirpath, d) not in skip] + for name in files: + with open(os.path.join(dirpath, name), "rb") as f: + if word.search(f.read().decode("utf-8", "ignore")): + return True + return False + + +def naming(all_scenarios, variable, root="."): + """The scenarios a change to the image pin `variable` reaches. + + Those with a file naming it; every scenario when a shared file names it or a file cannot + be read. + """ + word = re.compile(r"\b" + re.escape(variable) + r"\b") + scenarios = {os.path.join(root, s) for s in all_scenarios} + shared = [d for g in SHARED for d in glob.glob(os.path.join(root, g))] + try: + if any(_names(d, word, scenarios) for d in shared if os.path.isdir(d)): + return list(all_scenarios) + return [s for s in all_scenarios if _names(os.path.join(root, s), word)] + except OSError: + return list(all_scenarios) + + def is_ignored(path): return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED) -def select(all_scenarios, changed, root="."): +def reason_for(changed_roles, roles, extensions, image_pins): + """The one-line reason select() gives for its choice.""" + notes = [] + if roles: + notes.append( + "roles changed: " + ", ".join(printable(r) for r in sorted(changed_roles)) + ) + if roles - changed_roles: + notes.append( + "their users: " + + ", ".join(printable(r) for r in sorted(roles - changed_roles)) + ) + if extensions: + notes.append( + "image-smoke scenarios changed: " + + ", ".join(printable(e.split("/")[2]) for e in sorted(extensions)) + ) + if image_pins: + notes.append("image pins changed: " + ", ".join(sorted(image_pins))) + return "; ".join(notes) or "no change that a scenario reads" + + +def select(all_scenarios, changed, root=".", pins=None): """The scenarios `changed` (repository-relative paths) needs, and a one-line reason. + `pins` is pin_changes() of WORKFLOW; None when it is not narrowed. Raises ValueError when a changed role still exists but has no scenario. """ roles = set() extensions = set() + by_image = set() + image_pins = set() for path in changed: if is_ignored(path): continue + if path == WORKFLOW and pins is not None and "CI_IMAGE" not in pins: + image_pins = pins + for pin in pins: + by_image.update(naming(all_scenarios, pin, root)) + continue parts = path.split("/") if len(parts) > 2 and parts[0] == "roles": roles.add(parts[1]) @@ -219,7 +354,9 @@ def select(all_scenarios, changed, root="."): chosen = [ s for s in all_scenarios - if s in extensions or (s.startswith("roles/") and s.split("/")[1] in roles) + if s in extensions + or s in by_image + or (s.startswith("roles/") and s.split("/")[1] in roles) ] covered = {s.split("/")[1] for s in chosen if s.startswith("roles/")} bare = sorted( @@ -230,23 +367,7 @@ def select(all_scenarios, changed, root="."): "role without a molecule scenario (changed, or a user of a changed role): " + ", ".join(printable(r) for r in bare) ) - notes = [] - if roles: - notes.append( - "roles changed: " + ", ".join(printable(r) for r in sorted(changed_roles)) - ) - if roles - changed_roles: - notes.append( - "their users: " - + ", ".join(printable(r) for r in sorted(roles - changed_roles)) - ) - if extensions: - notes.append( - "image-smoke scenarios changed: " - + ", ".join(printable(e.split("/")[2]) for e in sorted(extensions)) - ) - reason = "; ".join(notes) or "no change that a scenario reads" - return chosen, reason + return chosen, reason_for(changed_roles, roles, extensions, image_pins) def changed_paths(base_ref): @@ -267,6 +388,23 @@ def changed_paths(base_ref): return [os.fsdecode(p) for p in out.split(b"\0") if p] +def workflow_pins(base_ref, changed): + """pin_changes() of WORKFLOW from the merge base to HEAD; None on any doubt.""" + if WORKFLOW not in changed: + return None + + def git(*args): + return subprocess.run(["git", *args], check=True, capture_output=True).stdout + + try: + base = git("merge-base", base_ref, "HEAD").decode("ascii").strip() + old = git("show", f"{base}:{WORKFLOW}").decode("utf-8") + new = git("show", f"HEAD:{WORKFLOW}").decode("utf-8") + except (subprocess.CalledProcessError, OSError, UnicodeError): + return None + return pin_changes(old, new) + + def main(argv, environ=None): environ = os.environ if environ is None else environ if len(argv) > 2: @@ -294,7 +432,8 @@ def main(argv, environ=None): chosen = scenarios else: try: - chosen, reason = select(scenarios, changed) + pins = workflow_pins(base_ref, changed) + chosen, reason = select(scenarios, changed, pins=pins) except ValueError as exc: print(f"::error::{exc}", file=sys.stderr) return 1 diff --git a/tests/scripts/test_select_molecule_scenarios.py b/tests/scripts/test_select_molecule_scenarios.py index d4031b0..f7f7808 100644 --- a/tests/scripts/test_select_molecule_scenarios.py +++ b/tests/scripts/test_select_molecule_scenarios.py @@ -452,6 +452,41 @@ class MainTest(unittest.TestCase): finally: os.chdir(cwd) + IMG = "git.rkdr.net/mortis/molecule-ubuntu2604:0.1.1@sha256:" + "a" * 64 + WORKFLOW_BASE = ( + f"env:\n # a comment\n MOLECULE_IMAGE_2604: >-\n {IMG}\nrun: x\n" + ) + + def run_workflow_topic(self, text): + with tempfile.TemporaryDirectory() as root: + pathlib.Path(root, ".gitea/workflows").mkdir(parents=True) + pathlib.Path(root, sel.WORKFLOW).write_text(self.WORKFLOW_BASE) + self.topic_repo(root, {sel.WORKFLOW: text}) + cwd = os.getcwd() + os.chdir(root) + try: + return self.run_main(["main"], {"EVENT_NAME": "pull_request"}) + finally: + os.chdir(cwd) + + def test_a_comment_only_change_selects_nothing(self): + code, out, _err = self.run_workflow_topic( + self.WORKFLOW_BASE.replace("a comment", "other") + ) + self.assertEqual((code, out), (0, [])) + + def test_a_pin_change_selects_by_image_and_another_change_everything(self): + code, out, err = self.run_workflow_topic( + self.WORKFLOW_BASE.replace(self.IMG, self.IMG.replace("0.1.1", "0.1.2")) + ) + # make_repo's scenarios name no image, so the 2604 pin reaches none of them + self.assertEqual((code, out), (0, [])) + self.assertIn("image pins changed: MOLECULE_IMAGE_2604", err) + code, out, _err = self.run_workflow_topic( + self.WORKFLOW_BASE.replace("run: x", "run: y") + ) + self.assertEqual((code, len(out)), (0, 3)) + def test_empty_base_ref_argument_runs_all(self): with tempfile.TemporaryDirectory() as root: self.make_repo(root) @@ -609,5 +644,202 @@ class MainTest(unittest.TestCase): self.assertTrue(all((REPO / d / "molecule.yml").is_file() for d in found)) +class WorkflowPinsTest(unittest.TestCase): + WORKFLOW = (REPO / sel.WORKFLOW).read_text() + + def edited(self, old, new): + self.assertIn(old, self.WORKFLOW) + return sel.pin_changes(self.WORKFLOW, self.WORKFLOW.replace(old, new, 1)) + + def pin(self, key): + lines = self.WORKFLOW.splitlines() + return lines[lines.index(f" {key}: >-") + 1].strip() + + def bumped(self, key): + """The pin of `key` at another digest, as Renovate would write it.""" + return self.pin(key).split("@sha256:")[0] + "@sha256:" + "0" * 64 + + def test_the_workflow_has_each_pin_where_the_selector_looks(self): + for key in ("CI_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"): + self.assertEqual(self.edited(self.pin(key), self.bumped(key)), {key}, key) + + def test_comments_and_blank_lines_change_nothing(self): + self.assertEqual(self.edited("# Behavioural tests", "# Other words"), set()) + self.assertEqual(self.edited("\njobs:\n", "\n\n\njobs:\n"), set()) + self.assertEqual( + self.edited( + " # Used by the scenarios", " # Read by the scenarios" + ), + set(), + ) + + def test_a_hash_line_inside_a_block_scalar_is_content(self): + # In a `run: |` script a `#` line may be heredoc content, not a comment. + self.assertIsNone( + self.edited(" # Assigned first", " # Set first") + ) + + def test_two_pins(self): + changed = sel.pin_changes( + self.WORKFLOW, + self.WORKFLOW.replace( + self.pin("MOLECULE_IMAGE"), self.bumped("MOLECULE_IMAGE") + ).replace( + self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604") + ), + ) + self.assertEqual(changed, {"MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"}) + + def test_a_pin_value_is_the_next_line_in_renovates_shape(self): + value = self.pin("MOLECULE_IMAGE") + indent = " " * 8 + for new in ( + # YAML folds the comment into the value: '# x git.rkdr.net/...' + f"{indent}# x\n{indent}{value}", + f"\n{indent}{value}", + f"{indent}{value}\n{indent}more", + f"{indent}other:1", + value, + ): + self.assertIsNone(self.edited(f"{indent}{value}", new), new) + + def test_a_value_line_replaced_by_an_env_key_is_not_narrowed(self): + self.assertIsNone( + self.edited( + " " + self.pin("MOLECULE_IMAGE_2604"), + " MOLECULE_IMAGE: other:1", + ) + ) + + def test_any_other_change_is_not_narrowed(self): + for old, new in ( + ("timeout-minutes: 90", "timeout-minutes: 60"), + (" MOLECULE_IMAGE_2604: >-", " MOLECULE_IMAGE_2605: >-"), + (" MOLECULE_IMAGE: >-", " MOLECULE_IMAGE: >"), + ("-e MOLECULE_IMAGE -e", "-e"), + ( + " # Every scenario, nightly", + " schedule: []\n # Every scenario, nightly", + ), + ("--init", "--init # not a comment line"), + ): + self.assertIsNone(self.edited(old, new), old) + + def test_a_pin_and_another_change_is_not_narrowed(self): + text = self.WORKFLOW.replace( + self.pin("MOLECULE_IMAGE_2604"), self.bumped("MOLECULE_IMAGE_2604") + ).replace("timeout-minutes: 90", "timeout-minutes: 60") + self.assertIsNone(sel.pin_changes(self.WORKFLOW, text)) + + +SCENARIO_IMAGES = { + "extensions/molecule/image-smoke": "image: ${MOLECULE_IMAGE}", + "extensions/molecule/image-smoke-2604": "image: ${MOLECULE_IMAGE_2604}", + "roles/docker/molecule/default": "${MOLECULE_IMAGE} ${MOLECULE_IMAGE_2604}", + "roles/fail2ban/molecule/default": "image: ${MOLECULE_IMAGE}", + "roles/system_baseline/molecule/default": "image: ubuntu:24.04", +} + + +class SelectByPinTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = tmp.name + for scenario, text in SCENARIO_IMAGES.items(): + pathlib.Path(self.root, scenario).mkdir(parents=True) + pathlib.Path(self.root, scenario, "molecule.yml").write_text(text) + + def select(self, pins, changed=(sel.WORKFLOW,)): + return sel.select(ALL, list(changed), self.root, pins)[0] + + def test_a_2604_pin_selects_the_scenarios_naming_it(self): + self.assertEqual( + self.select({"MOLECULE_IMAGE_2604"}), + ["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"], + ) + + def test_a_2404_pin_does_not_match_the_2604_name(self): + self.assertEqual( + self.select({"MOLECULE_IMAGE"}), + [ + "extensions/molecule/image-smoke", + "roles/docker/molecule/default", + "roles/fail2ban/molecule/default", + ], + ) + + def test_comments_only_select_nothing(self): + self.assertEqual(self.select(set()), []) + + def test_the_ci_image_or_no_analysis_selects_everything(self): + self.assertEqual(self.select({"CI_IMAGE", "MOLECULE_IMAGE"}), ALL) + self.assertEqual(self.select(None), ALL) + + def test_pins_do_not_narrow_another_file(self): + self.assertEqual(self.select(set(), [sel.WORKFLOW, "meta/runtime.yml"]), ALL) + self.assertEqual(self.select(set(), ["meta/runtime.yml"]), ALL) + + def test_a_shared_file_naming_the_pin_selects_everything(self): + for shared in ( + ".config/molecule/config.yml", + "extensions/molecule/shared/vars.yml", + "roles/docker/molecule/resources/prepare.yml", + ): + path = pathlib.Path(self.root, shared) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("image: ${MOLECULE_IMAGE_2604}") + try: + self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, shared) + finally: + path.unlink() + + def test_a_shared_file_not_naming_the_pin_narrows(self): + path = pathlib.Path(self.root, ".config/molecule/config.yml") + path.parent.mkdir(parents=True) + path.write_text("image: ${MOLECULE_IMAGE}") + self.assertEqual( + self.select({"MOLECULE_IMAGE_2604"}), + ["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"], + ) + + def test_an_unreadable_scenario_selects_everything(self): + shutil.rmtree(pathlib.Path(self.root, "roles/fail2ban/molecule/default")) + self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL) + + def test_a_symlink_selects_everything(self): + # os.walk does not follow a directory symlink, so its target would go unread. + target = pathlib.Path(self.root, "elsewhere") + target.mkdir() + (target / "vars.yml").write_text("image: ${MOLECULE_IMAGE_2604}") + for link in ( + "roles/fail2ban/molecule/default/shared", + "extensions/molecule/shared", + ): + path = pathlib.Path(self.root, link) + path.symlink_to(target, target_is_directory=True) + try: + self.assertEqual(self.select({"MOLECULE_IMAGE_2604"}), ALL, link) + finally: + path.unlink() + self.assertEqual( + self.select({"MOLECULE_IMAGE_2604"}), + ["extensions/molecule/image-smoke-2604", "roles/docker/molecule/default"], + ) + + def test_pins_combine_with_a_role(self): + self.assertEqual( + self.select( + {"MOLECULE_IMAGE_2604"}, + [sel.WORKFLOW, "roles/system_baseline/tasks/main.yml"], + ), + [ + "extensions/molecule/image-smoke-2604", + "roles/docker/molecule/default", + "roles/system_baseline/molecule/default", + ], + ) + + if __name__ == "__main__": unittest.main() From 2e70980b4473cbd6e2bd9e39021e6c6dce31f51c Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 14:13:31 +0000 Subject: [PATCH 24/26] test: check refusals once on the controller in verify converge.yml is replayed by check, converge, check and idempotence on both platforms, so the validation-only plays in it ran eight times per scenario. They need no container: move them to the top of verify.yml, on localhost in check mode, so they run once and a regressed refusal cannot change the controller. Applies to the default scenarios of system_baseline, docker, sshd and systemd_hardening. The systemd_hardening refusal of a drop-in entry that is not a mapping comes after the disable and mask tasks, so it moves to verify.yml but stays on the container. The README Tests sections say where each check now runs. Assisted-by: Claude Code:claude-opus-5-5 --- changelogs/fragments/refusals-in-verify.yml | 6 + roles/docker/molecule/default/converge.yml | 113 ------ roles/docker/molecule/default/verify.yml | 129 +++++++ roles/sshd/README.md | 4 +- roles/sshd/molecule/default/converge.yml | 70 ---- roles/sshd/molecule/default/verify.yml | 79 ++++- roles/system_baseline/README.md | 8 +- .../molecule/default/converge.yml | 304 ---------------- .../molecule/default/verify.yml | 334 ++++++++++++++++++ .../molecule/default/converge.yml | 88 ----- .../molecule/default/verify.yml | 95 +++++ 11 files changed, 648 insertions(+), 582 deletions(-) create mode 100644 changelogs/fragments/refusals-in-verify.yml diff --git a/changelogs/fragments/refusals-in-verify.yml b/changelogs/fragments/refusals-in-verify.yml new file mode 100644 index 0000000..b5791aa --- /dev/null +++ b/changelogs/fragments/refusals-in-verify.yml @@ -0,0 +1,6 @@ +--- +trivial: + - >- + docker, sshd, system_baseline, systemd_hardening - The Molecule scenarios check the refusals and the + accepted inputs once, on the controller, in verify instead of in every converge run; the README Tests + sections say so. diff --git a/roles/docker/molecule/default/converge.yml b/roles/docker/molecule/default/converge.yml index d0cb6e8..652e5bd 100644 --- a/roles/docker/molecule/default/converge.yml +++ b/roles/docker/molecule/default/converge.yml @@ -20,116 +20,3 @@ max-concurrent-downloads: 3 roles: - role: mortis.kamino.docker - -# The plays below are refusals: argument_specs rejects the wrong types before any task runs, -# so the idempotence run stays clean. A sentinel in the failure message tells "the role -# refused" from "the fail task after the role ran", which a bare rescue cannot. -- name: A docker_users value that is not a list is refused - hosts: all - gather_facts: false - vars: - docker_users: - not: a-list - tasks: - - name: Apply the role with a mapping for docker_users - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.docker - - name: Fail when the wrong type was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The argument check stopped the play - ansible.builtin.assert: - that: - - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - - "'docker_users' in ansible_failed_result.msg | default('')" - quiet: true - -- name: A docker_remove value that is not a boolean is refused - hosts: all - gather_facts: false - vars: - docker_remove: maybe - tasks: - - name: Apply the role with a non-boolean docker_remove - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.docker - - name: Fail when the wrong type was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The argument check stopped the play - ansible.builtin.assert: - that: - - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - - "'docker_remove' in ansible_failed_result.msg | default('')" - quiet: true - -# The architecture is written into the one-line apt source, so a value with a space or a bracket is refused before anything -# changes. The derived default is covered by the converge above and verify.yml (the container is x86_64, so the source says amd64). -- name: A docker_apt_arch value that would corrupt the apt source is refused - hosts: all - gather_facts: false - vars: - docker_apt_arch: "bad arch" - tasks: - - name: Apply the role with a bad architecture - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.docker - - name: Fail when the bad architecture was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: - - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - - "'docker_apt_arch' in ansible_failed_result.msg | default('')" - quiet: true - -# The unit timings are checked before anything changes. -- name: A docker_stop_at_shutdown_timeout of 0 is refused - hosts: all - gather_facts: false - vars: - docker_stop_at_shutdown_timeout: 0 - tasks: - - name: Apply the role with a timeout of 0 - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.docker - - name: Fail when the timeout was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: - - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - - "'docker_stop_at_shutdown_timeout' in ansible_failed_result.msg | default('')" - quiet: true - -# A key that docker_daemon_options and a dedicated input both set, and a log value dockerd would reject, stop the run before any change. -- name: A bad daemon setting is refused - hosts: all - gather_facts: false - tasks: - - name: Apply the role with each bad setting - ansible.builtin.include_tasks: tasks/refuse_daemon.yml - vars: - docker_refused: "{{ item }}" - loop: - - {docker_live_restore: true, docker_daemon_options: {live-restore: false}} - - {docker_log_driver: local, docker_daemon_options: {log-driver: json-file}} - - {docker_log_max_size: 10m, docker_daemon_options: {log-opts: {max-size: 1m}}} - - {docker_log_driver: Local} - - {docker_log_max_size: ten} - - {docker_log_max_file: "0"} - - {docker_log_max_file: "-1"} diff --git a/roles/docker/molecule/default/verify.yml b/roles/docker/molecule/default/verify.yml index 522fc5d..70bef8a 100644 --- a/roles/docker/molecule/default/verify.yml +++ b/roles/docker/molecule/default/verify.yml @@ -1,4 +1,133 @@ --- +# The refusals need no container, so they run once, on the controller, in check mode so that a +# refusal that regressed cannot change it. The controller has no gathered facts, so a play that +# does not test the architecture sets it. A sentinel in the failure message tells "the role +# refused" from "the fail task after the role ran", which a bare rescue cannot. +- name: A docker_users value that is not a list is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + docker_apt_arch: amd64 + docker_users: + not: a-list + tasks: + - name: Apply the role with a mapping for docker_users + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.docker + - name: Fail when the wrong type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The argument check stopped the play + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'docker_users' in ansible_failed_result.msg | default('')" + quiet: true + +- name: A docker_remove value that is not a boolean is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + docker_apt_arch: amd64 + docker_remove: maybe + tasks: + - name: Apply the role with a non-boolean docker_remove + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.docker + - name: Fail when the wrong type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The argument check stopped the play + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'docker_remove' in ansible_failed_result.msg | default('')" + quiet: true + +# The architecture is written into the one-line apt source, so a value with a space or a bracket is refused before anything +# changes. The derived default is covered by converge.yml and the plays below (the container is x86_64, so the source says amd64). +- name: A docker_apt_arch value that would corrupt the apt source is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + docker_apt_arch: "bad arch" + tasks: + - name: Apply the role with a bad architecture + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.docker + - name: Fail when the bad architecture was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'docker_apt_arch' in ansible_failed_result.msg | default('')" + quiet: true + +# The unit timings are checked before anything changes. +- name: A docker_stop_at_shutdown_timeout of 0 is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + docker_apt_arch: amd64 + docker_stop_at_shutdown_timeout: 0 + tasks: + - name: Apply the role with a timeout of 0 + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.docker + - name: Fail when the timeout was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'docker_stop_at_shutdown_timeout' in ansible_failed_result.msg | default('')" + quiet: true + +# A key that docker_daemon_options and a dedicated input both set, and a log value dockerd would reject, stop the run before any change. +- name: A bad daemon setting is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + docker_apt_arch: amd64 + tasks: + - name: Apply the role with each bad setting + ansible.builtin.include_tasks: tasks/refuse_daemon.yml + vars: + docker_refused: "{{ item }}" + loop: + - {docker_live_restore: true, docker_daemon_options: {live-restore: false}} + - {docker_log_driver: local, docker_daemon_options: {log-driver: json-file}} + - {docker_log_max_size: 10m, docker_daemon_options: {log-opts: {max-size: 1m}}} + - {docker_log_driver: Local} + - {docker_log_max_size: ten} + - {docker_log_max_file: "0"} + - {docker_log_max_file: "-1"} + # What the role is for, as far as stand-in packages can show it: the repository key and the # source line are in place and apt really used them, the packages are installed from that # repository, the unit is enabled and running, and the user joined the group. The second play diff --git a/roles/sshd/README.md b/roles/sshd/README.md index 7b20144..720ae26 100644 --- a/roles/sshd/README.md +++ b/roles/sshd/README.md @@ -61,8 +61,8 @@ The role defines none. The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_IMAGE}` (Ubuntu 24.04) and `${MOLECULE_IMAGE_2604}` (Ubuntu 26.04). Both images ship openssh-server. It runs `check` before the converge (a fresh host) and after it (a configured host). -- Converge applies the `ubuntu_lxc` profile. It then loads the defaults through `tasks_from: validate.yml` without changing the host: every profile (`pve`, `ubuntu_lxc`, `ubuntu_vm`) passes validation and keeps its root login policy and key algorithms, a consumer `sshd_settings` override wins over the profile, and the `pve` guard accepts each value that allows root key login. -- Verify first checks the refusals: a run without `sshd_profile`, `PubkeyAuthentication no` (lock-out), a `pve` profile with `PermitRootLogin no` or `forced-commands-only`, a `pve` profile without `rsa-sha2-512`, SHA-1 `ssh-rsa`, and an unknown profile. Each but the missing profile is matched on its message. +- Converge applies the `ubuntu_lxc` profile. Verify first loads the defaults on the controller through `tasks_from: validate.yml`: every profile (`pve`, `ubuntu_lxc`, `ubuntu_vm`) passes validation and keeps its root login policy and key algorithms, a consumer `sshd_settings` override wins over the profile, and the `pve` guard accepts each value that allows root key login. +- Verify then checks the refusals: a run without `sshd_profile`, `PubkeyAuthentication no` (lock-out), a `pve` profile with `PermitRootLogin no` or `forced-commands-only`, a `pve` profile without `rsa-sha2-512`, SHA-1 `ssh-rsa`, and an unknown profile. Each but the missing profile is matched on its message. - Verify then checks the converged host: the drop-in exists, `sshd -t` passes, the `ssh` unit is active, and `sshd -T` shows key login on and password and root login off. - The `pve` profile is checked by rendering its drop-in to a scratch file and parsing it with `sshd -T -f`: root logs in with keys only and passwords stay off. diff --git a/roles/sshd/molecule/default/converge.yml b/roles/sshd/molecule/default/converge.yml index 05d21b2..dc5401a 100644 --- a/roles/sshd/molecule/default/converge.yml +++ b/roles/sshd/molecule/default/converge.yml @@ -7,73 +7,3 @@ ansible_user: root roles: - role: mortis.kamino.sshd - -# The plays below only load the role's defaults and run validate.yml, which changes nothing -# on the container. They cover the profiles the converge above cannot run and the values -# the guards accept. -- name: Every profile passes validation and keeps its root login policy - hosts: all - gather_facts: false - tasks: - - name: Validate each profile - ansible.builtin.include_role: - name: mortis.kamino.sshd - tasks_from: validate.yml - public: true - vars: - sshd_profile: "{{ item }}" - loop: [pve, ubuntu_lxc, ubuntu_vm] - - name: Assert the profile data - ansible.builtin.assert: - that: - - sshd_profiles.pve.PermitRootLogin == "prohibit-password" - - sshd_profiles.ubuntu_lxc.PermitRootLogin == "no" - - sshd_profiles.ubuntu_vm.PermitRootLogin == "no" - quiet: true - # Proxmox cluster SSH needs RSA with SHA-2, never SHA-1 ssh-rsa; the others stay ed25519 only. - - name: Assert the key algorithms per profile - ansible.builtin.assert: - that: - - sshd_profiles.pve.HostKeyAlgorithms == "ssh-ed25519,rsa-sha2-512,rsa-sha2-256" - - sshd_profiles.pve.PubkeyAcceptedAlgorithms == "ssh-ed25519,rsa-sha2-512,rsa-sha2-256" - - sshd_settings_defaults.HostKeyAlgorithms == "ssh-ed25519" - - sshd_settings_defaults.PubkeyAcceptedAlgorithms == "ssh-ed25519" - - "'HostKeyAlgorithms' not in sshd_profiles.ubuntu_lxc" - - "'HostKeyAlgorithms' not in sshd_profiles.ubuntu_vm" - quiet: true - -# Play vars outrank the role defaults, so the override reaches the merged settings. -- name: A consumer override wins and keeps the rest - hosts: all - gather_facts: false - vars: - sshd_profile: ubuntu_vm - sshd_settings: - MaxAuthTries: "5" - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.sshd - tasks_from: validate.yml - public: true - - name: Assert the override - ansible.builtin.assert: - that: - - sshd_settings_effective.MaxAuthTries == "5" - - sshd_settings_effective.PermitRootLogin == "no" - - sshd_settings_effective.PubkeyAuthentication == "yes" - quiet: true - -- name: The Proxmox guard accepts every value that allows root key login - hosts: all - gather_facts: false - tasks: - - name: Validate the pve profile with each accepted value - ansible.builtin.include_role: - name: mortis.kamino.sshd - tasks_from: validate.yml - vars: - sshd_profile: pve - sshd_settings: - PermitRootLogin: "{{ item }}" - loop: [prohibit-password, without-password, "yes", Prohibit-Password] diff --git a/roles/sshd/molecule/default/verify.yml b/roles/sshd/molecule/default/verify.yml index 67001d3..e20e9be 100644 --- a/roles/sshd/molecule/default/verify.yml +++ b/roles/sshd/molecule/default/verify.yml @@ -1,6 +1,83 @@ --- +# The plays below only load the role's defaults and run validate.yml, which needs no container, +# so they run once, on the controller, in check mode so that a regressed guard cannot change it. +# They cover the profiles converge.yml cannot run and the values the guards accept. +- name: Every profile passes validation and keeps its root login policy + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Validate each profile + ansible.builtin.include_role: + name: mortis.kamino.sshd + tasks_from: validate.yml + public: true + vars: + sshd_profile: "{{ item }}" + loop: [pve, ubuntu_lxc, ubuntu_vm] + - name: Assert the profile data + ansible.builtin.assert: + that: + - sshd_profiles.pve.PermitRootLogin == "prohibit-password" + - sshd_profiles.ubuntu_lxc.PermitRootLogin == "no" + - sshd_profiles.ubuntu_vm.PermitRootLogin == "no" + quiet: true + # Proxmox cluster SSH needs RSA with SHA-2, never SHA-1 ssh-rsa; the others stay ed25519 only. + - name: Assert the key algorithms per profile + ansible.builtin.assert: + that: + - sshd_profiles.pve.HostKeyAlgorithms == "ssh-ed25519,rsa-sha2-512,rsa-sha2-256" + - sshd_profiles.pve.PubkeyAcceptedAlgorithms == "ssh-ed25519,rsa-sha2-512,rsa-sha2-256" + - sshd_settings_defaults.HostKeyAlgorithms == "ssh-ed25519" + - sshd_settings_defaults.PubkeyAcceptedAlgorithms == "ssh-ed25519" + - "'HostKeyAlgorithms' not in sshd_profiles.ubuntu_lxc" + - "'HostKeyAlgorithms' not in sshd_profiles.ubuntu_vm" + quiet: true + +# Play vars outrank the role defaults, so the override reaches the merged settings. +- name: A consumer override wins and keeps the rest + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + sshd_profile: ubuntu_vm + sshd_settings: + MaxAuthTries: "5" + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.sshd + tasks_from: validate.yml + public: true + - name: Assert the override + ansible.builtin.assert: + that: + - sshd_settings_effective.MaxAuthTries == "5" + - sshd_settings_effective.PermitRootLogin == "no" + - sshd_settings_effective.PubkeyAuthentication == "yes" + quiet: true + +- name: The Proxmox guard accepts every value that allows root key login + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Validate the pve profile with each accepted value + ansible.builtin.include_role: + name: mortis.kamino.sshd + tasks_from: validate.yml + vars: + sshd_profile: pve + sshd_settings: + PermitRootLogin: "{{ item }}" + loop: [prohibit-password, without-password, "yes", Prohibit-Password] + # The refusal cases: here, not in converge.yml, because idempotence reruns converge. Each -# fails in validate.yml; they run first, so the assertions below also show the host unchanged. +# fails in validate.yml; they run before the host checks, so the assertions below also show the +# host unchanged. # A play without sshd_profile: the role must refuse it. The block proves the refusal # (not its wording). diff --git a/roles/system_baseline/README.md b/roles/system_baseline/README.md index a5f2dd9..f3cef36 100644 --- a/roles/system_baseline/README.md +++ b/roles/system_baseline/README.md @@ -128,12 +128,12 @@ The two task files besides `main` are a supported interface, for a caller that d The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_IMAGE}` (Ubuntu 24.04) and `${MOLECULE_IMAGE_2604}` (Ubuntu 26.04). It installs packages from the Ubuntu mirrors, so the runner needs outbound network. It runs `check` before the converge (a fresh host) and after it (a configured host). -- Converge first checks that the role refuses a bad input with its own message before any change: an unknown `system_baseline_system_type`, an unknown `system_baseline_apt_upgrade` (main flow and `update` entry point), a negative reboot throttle or a negative or boolean post-reboot delay (main flow and `reboot` entry point), a line break in `system_baseline_apt_daily_timeout`, a bad `system_baseline_journal_max_use` (a bare number, a space, a line break, a number), and a bad package blacklist (a quote, a null item, a bare string). -- Converge then applies the `ubuntu_lxc` profile, with tmux autostart and `system_baseline_apt_daily_timeout: 1h`, and only resolves the `pve` and `ubuntu_vm` profiles and a consumer override, asserting the resolved inputs. +- Verify first checks, on the controller, that the role refuses a bad input with its own message before any change: an unknown `system_baseline_system_type`, an unknown `system_baseline_apt_upgrade` (main flow and `update` entry point), a negative reboot throttle or a negative or boolean post-reboot delay (main flow and `reboot` entry point), a line break in `system_baseline_apt_daily_timeout`, a bad `system_baseline_journal_max_use` (a bare number, a space, a line break, a number), and a bad package blacklist (a quote, a null item, a bare string). +- Converge applies the `ubuntu_lxc` profile, with tmux autostart and `system_baseline_apt_daily_timeout: 1h`. Verify only resolves the `pve` and `ubuntu_vm` profiles and a consumer override, on the controller, asserting the resolved inputs. - Verify checks the installed and removed packages, the journal size cap, the apt settings in `20auto-upgrades` and `50unattended-upgrades`, the locale, and that systemd loaded the `apt-daily.service` timeout. - Verify checks the tmux snippet: root-owned, valid shell, the session and quoted window command, no effect without a terminal, a session name or window command ending in a newline refused, and the file removed when autostart is off. -- Converge refuses bad items in `system_baseline_extra_packages` and `system_baseline_extra_remove_packages` (whitespace, a null, an empty string, a trailing minus, upper case, a bare string) and a package that one input installs and another purges, then applies the `ubuntu_lxc` profile with `jq` as an extra package and `ed` as an extra removal; verify checks that `jq` is installed, `ed` is gone and the profile's packages are still there, and that an extra `tmux` installs the snippet where a flat list without it installs none. -- Converge also checks that a bad `system_baseline_apt_tmpdir` (under `/tmp` or `/var/tmp`, relative, with `..`, empty) is refused in the main flow and in the `update` entry point. Verify reads `tasks/update.yml` and checks that the scratch directory is created with mode `0700`, that both apt tasks set `TMPDIR` to it, and that the connection is reset afterwards: the scenario skips the `update` tag, so the upgrade itself never runs there. +- Verify refuses bad items in `system_baseline_extra_packages` and `system_baseline_extra_remove_packages` (whitespace, a null, an empty string, a trailing minus, upper case, a bare string) and a package that one input installs and another purges; converge applies the `ubuntu_lxc` profile with `jq` as an extra package and `ed` as an extra removal; verify checks that `jq` is installed, `ed` is gone and the profile's packages are still there, and that an extra `tmux` installs the snippet where a flat list without it installs none. +- Verify also checks that a bad `system_baseline_apt_tmpdir` (under `/tmp` or `/var/tmp`, relative, with `..`, empty) is refused in the main flow and in the `update` entry point. It reads `tasks/update.yml` and checks that the scratch directory is created with mode `0700`, that both apt tasks set `TMPDIR` to it, and that the connection is reset afterwards: the scenario skips the `update` tag, so the upgrade itself never runs there. - Verify ends by running the role once with `system_baseline_journal_max_use: ""` after removing the drop-in, and asserts that no drop-in is written and that `systemd-journald` was not restarted. - Verify runs the `reboot` entry point with `system_baseline_reboot_if_required: false`, without and with `/var/run/reboot-required`, and checks the fact and that the host did not reboot. - The `pve` origins pin is applied to the Ubuntu container and read back with `apt-config dump`, then removed again. The package blacklist is written, read back as a list, left alone by a second run and removed by an empty list. diff --git a/roles/system_baseline/molecule/default/converge.yml b/roles/system_baseline/molecule/default/converge.yml index 11bb7b4..be9aa95 100644 --- a/roles/system_baseline/molecule/default/converge.yml +++ b/roles/system_baseline/molecule/default/converge.yml @@ -1,181 +1,4 @@ --- -- name: Refuse an unknown system_baseline_system_type - hosts: all - gather_facts: false - tasks: - - name: Run the role with a bad system_baseline_system_type - block: - - name: Include system_baseline - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - vars: - system_baseline_system_type: not_a_type - - name: Unreachable when validation works - ansible.builtin.fail: - msg: system_baseline ran with an invalid system_baseline_system_type - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: "'is invalid' in ansible_failed_result.msg | default('')" - quiet: true - -# The apt upgrade mode is safe or dist: anything else (here `full`, an apt module value the role does not offer) stops the run before -# any change, with a message that names the input. -- name: An unknown apt upgrade mode is refused - hosts: all - gather_facts: false - tasks: - - name: Run the role with a bad system_baseline_apt_upgrade - block: - - name: Include system_baseline - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - vars: - system_baseline_system_type: ubuntu_lxc - system_baseline_apt_upgrade: full - - name: Unreachable when validation works - ansible.builtin.fail: - msg: system_baseline ran with an invalid system_baseline_apt_upgrade - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: "'system_baseline_apt_upgrade is' in ansible_failed_result.msg | default('')" - quiet: true - -# The update entry point does not run validate.yml, so it checks the mode itself and stops before it calls the package module. -- name: The update entry point refuses an unknown apt upgrade mode - hosts: all - gather_facts: false - tasks: - - name: Run the update entry point with a bad system_baseline_apt_upgrade - block: - - name: Include system_baseline, tasks_from update - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: update - vars: - system_baseline_apt_upgrade: full - - name: Unreachable when validation works - ansible.builtin.fail: - msg: the update entry point ran with an invalid system_baseline_apt_upgrade - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: "'system_baseline_apt_upgrade is' in ansible_failed_result.msg | default('')" - quiet: true - -# The apt scratch directory becomes TMPDIR of the upgrade: a path under /tmp or /var/tmp (which a restart of ssh.service can delete), a relative -# path and a `..` each stop the run before any change, in the main flow and in the update entry point (which does not run validate.yml). -- name: A bad apt scratch directory is refused - hosts: all - gather_facts: false - tasks: - - name: Refuse each bad value - ansible.builtin.include_tasks: tasks/refuse_apt_tmpdir_entries.yml - vars: - system_baseline_refused_tmpdir: "{{ item }}" - loop: - - /tmp - - /var/tmp/apt - - /var/cache/../../tmp/x - - var/cache/apt-tmp - - "" - -# The reboot inputs are whole numbers, 0 or more: a negative number and a boolean each stop the run before a host reboots, -# in the main flow and in the reboot entry point (which does not run validate.yml). -- name: A bad reboot throttle or post-reboot delay is refused - hosts: all - gather_facts: false - tasks: - - name: Refuse each bad value - ansible.builtin.include_tasks: tasks/refuse_reboot.yml - vars: - system_baseline_refused_reboot: "{{ item }}" - loop: - - {system_baseline_reboot_throttle: -1} - - {system_baseline_reboot_post_delay: -5} - - {system_baseline_reboot_post_delay: true} - -# The value is written into a unit file, so a line break (a second directive) is refused. -- name: A bad apt-daily timeout is refused - hosts: all - gather_facts: false - tasks: - - name: Run the role with a line break in system_baseline_apt_daily_timeout - block: - - name: Include system_baseline - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - vars: - system_baseline_system_type: ubuntu_lxc - system_baseline_apt_daily_timeout: "1h\nExecStart=/bin/true" - - name: Unreachable when validation works - ansible.builtin.fail: - msg: system_baseline ran with an invalid system_baseline_apt_daily_timeout - rescue: - - name: The validation stopped the play - ansible.builtin.assert: - that: "'system_baseline_apt_daily_timeout must be' in ansible_failed_result.msg | default('')" - quiet: true - -# The journal cap is a number and a unit letter, or empty: a bare number (journald would read bytes), a zero, a space, a line break, a -# lower-case unit and a number that is not a string each stop the run before any change. -- name: A bad journal size cap is refused - hosts: all - gather_facts: false - tasks: - - name: Refuse each bad value - ansible.builtin.include_tasks: tasks/refuse_journal_max_use.yml - vars: - system_baseline_refused_journal: "{{ item }}" - loop: - - "300" - - "0" - - 10 M - - "10m" - - "200M\nStorage=none" - - 300 - -# A quote, a null item and a bare string (not a list) each stop the run: the bare string would otherwise be split into one-character -# patterns, and the null item would become an empty pattern that matches every package. -- name: A bad package blacklist is refused - hosts: all - gather_facts: false - tasks: - - name: Refuse each bad value - ansible.builtin.include_tasks: tasks/refuse_blacklist.yml - vars: - system_baseline_refused_blacklist: "{{ item }}" - loop: - - ['bad"name'] - - [null] - - linux-image-.* - -# Items that are not Debian package names (whitespace, null, empty, a trailing minus that apt reads as a removal, an option, upper case, a -# version pin), and a package that one input installs and another purges, each stop the run before any change. -# The overlaps are: an extra install against the profile's remove list (telnet), an extra install against an extra remove, and an extra -# remove against the profile's install list (tmux). -- name: A bad extra package list is refused - hosts: all - gather_facts: false - tasks: - - name: Refuse each bad value - ansible.builtin.include_tasks: tasks/refuse_extra_packages.yml - vars: - system_baseline_refused_case: "{{ item }}" - loop: - - { install: ['bad name'], expect: 'must be lists of package names' } - - { install: [null], expect: 'must be lists of package names' } - - { install: jq, expect: 'must be lists of package names' } - - { remove: [''], expect: 'must be lists of package names' } - - { install: ['jq-'], expect: 'must be lists of package names' } - - { install: ['-y'], expect: 'must be lists of package names' } - - { remove: ['Telnet'], expect: 'must be lists of package names' } - - { remove: ['ed=1.0'], expect: 'must be lists of package names' } - - { install: [telnet], expect: 'is both installed and purged' } - - { install: [jq], remove: [jq], expect: 'is both installed and purged' } - - { remove: [tmux], expect: 'is both installed and purged' } - - name: Converge the LXC profile hosts: all gather_facts: true @@ -190,130 +13,3 @@ - { name: logs, command: "echo 'a b'; true" } roles: - role: mortis.kamino.system_baseline - -# The remaining plays only load the role's defaults (validate.yml changes nothing) and assert -# the resolved inputs. They cover the profiles the converge above cannot run. -- name: The pve profile resolves - hosts: all - gather_facts: false - vars: - system_baseline_system_type: pve - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: validate.yml - public: true - - name: Assert the pve profile - ansible.builtin.assert: - that: - - "'ufw' not in system_baseline_essential_packages" - - "'tmux' not in system_baseline_essential_packages" - - "'unattended-upgrades' in system_baseline_essential_packages" - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00' - - system_baseline_secure_tmp_mounts == ['/dev/shm', '/tmp', '/var/tmp'] - - system_baseline_update - - system_baseline_apt_upgrade == 'dist' - - system_baseline_unattended_upgrade_origins | length == 3 - - system_baseline_unattended_upgrade_origins | select('search', 'Proxmox') | list == [] - - __system_baseline_install_packages == system_baseline_essential_packages - - __system_baseline_purge_packages == system_baseline_remove_packages - quiet: true - -- name: The ubuntu_vm profile resolves - hosts: all - gather_facts: false - vars: - system_baseline_system_type: ubuntu_vm - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: validate.yml - public: true - - name: Assert the ubuntu_vm profile - ansible.builtin.assert: - that: - - "'qemu-guest-agent' in system_baseline_essential_packages" - - "'tmux' in system_baseline_essential_packages" - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' - - system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1 - - system_baseline_apt_upgrade == 'safe' - - system_baseline_unattended_upgrade_origins == [] - - __system_baseline_install_packages == system_baseline_essential_packages - - __system_baseline_purge_packages == system_baseline_remove_packages - quiet: true - -# Consumer play vars override the profile. -- name: Consumer overrides win over the profile - hosts: all - gather_facts: false - vars: - system_baseline_system_type: ubuntu_vm - system_baseline_remove_packages: [telnet] - system_baseline_apt_upgrade: dist - system_baseline_profile_overrides: - ubuntu_vm: - unattended_upgrade_settings: - "Unattended-Upgrade::Automatic-Reboot": true - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: validate.yml - public: true - - name: Assert the overrides - ansible.builtin.assert: - that: - - system_baseline_remove_packages == ['telnet'] - - system_baseline_apt_upgrade == 'dist' - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == true - - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' - - "'qemu-guest-agent' in system_baseline_essential_packages" - quiet: true - -# The extras append to the resolved lists, whether the profile's list or a flat input supplies them, and a name that is in both is listed once. -- name: Extra packages append to the resolved lists - hosts: all - gather_facts: false - vars: - system_baseline_system_type: ubuntu_lxc - system_baseline_essential_packages: [vim, curl] - system_baseline_extra_packages: [jq, vim, unattended-upgrades] - system_baseline_extra_remove_packages: [ed, telnet] - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: validate.yml - public: true - - name: Assert the lists the role acts on - ansible.builtin.assert: - that: - - __system_baseline_install_packages == ['vim', 'curl', 'jq', 'unattended-upgrades'] - - "'ed' in __system_baseline_purge_packages" - - __system_baseline_purge_packages | select('equalto', 'telnet') | list | length == 1 - - system_baseline_remove_packages | difference(__system_baseline_purge_packages) | length == 0 - quiet: true - -# A flat input that is a plain string (the package module accepts one) still counts as a one-item list, with and without extras. -- name: A flat string package list still resolves - hosts: all - gather_facts: false - vars: - system_baseline_system_type: ubuntu_lxc - system_baseline_essential_packages: vim - system_baseline_extra_packages: [jq] - tasks: - - name: Load the role defaults - ansible.builtin.include_role: - name: mortis.kamino.system_baseline - tasks_from: validate.yml - public: true - - name: Assert the lists the role acts on - ansible.builtin.assert: - that: - - __system_baseline_install_packages == ['vim', 'jq'] - quiet: true diff --git a/roles/system_baseline/molecule/default/verify.yml b/roles/system_baseline/molecule/default/verify.yml index 7afc4b2..d4ccacb 100644 --- a/roles/system_baseline/molecule/default/verify.yml +++ b/roles/system_baseline/molecule/default/verify.yml @@ -1,4 +1,338 @@ --- +# Validation-only plays: they need no container, so they run once, on the controller, in +# check mode so that a refusal that regressed cannot change the controller. +- name: Refuse an unknown system_baseline_system_type + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Run the role with a bad system_baseline_system_type + block: + - name: Include system_baseline + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: not_a_type + - name: Unreachable when validation works + ansible.builtin.fail: + msg: system_baseline ran with an invalid system_baseline_system_type + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: "'is invalid' in ansible_failed_result.msg | default('')" + quiet: true + +# The apt upgrade mode is safe or dist: anything else (here `full`, an apt module value the role does not offer) stops the run before +# any change, with a message that names the input. +- name: An unknown apt upgrade mode is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Run the role with a bad system_baseline_apt_upgrade + block: + - name: Include system_baseline + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_apt_upgrade: full + - name: Unreachable when validation works + ansible.builtin.fail: + msg: system_baseline ran with an invalid system_baseline_apt_upgrade + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: "'system_baseline_apt_upgrade is' in ansible_failed_result.msg | default('')" + quiet: true + +# The update entry point does not run validate.yml, so it checks the mode itself and stops before it calls the package module. +- name: The update entry point refuses an unknown apt upgrade mode + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Run the update entry point with a bad system_baseline_apt_upgrade + block: + - name: Include system_baseline, tasks_from update + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: update + vars: + system_baseline_apt_upgrade: full + - name: Unreachable when validation works + ansible.builtin.fail: + msg: the update entry point ran with an invalid system_baseline_apt_upgrade + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: "'system_baseline_apt_upgrade is' in ansible_failed_result.msg | default('')" + quiet: true + +# The apt scratch directory becomes TMPDIR of the upgrade: a path under /tmp or /var/tmp (which a restart of ssh.service can delete), a relative +# path and a `..` each stop the run before any change, in the main flow and in the update entry point (which does not run validate.yml). +- name: A bad apt scratch directory is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_apt_tmpdir_entries.yml + vars: + system_baseline_refused_tmpdir: "{{ item }}" + loop: + - /tmp + - /var/tmp/apt + - /var/cache/../../tmp/x + - var/cache/apt-tmp + - "" + +# The reboot inputs are whole numbers, 0 or more: a negative number and a boolean each stop the run before a host reboots, +# in the main flow and in the reboot entry point (which does not run validate.yml). +- name: A bad reboot throttle or post-reboot delay is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_reboot.yml + vars: + system_baseline_refused_reboot: "{{ item }}" + loop: + - {system_baseline_reboot_throttle: -1} + - {system_baseline_reboot_post_delay: -5} + - {system_baseline_reboot_post_delay: true} + +# The value is written into a unit file, so a line break (a second directive) is refused. +- name: A bad apt-daily timeout is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Run the role with a line break in system_baseline_apt_daily_timeout + block: + - name: Include system_baseline + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_apt_daily_timeout: "1h\nExecStart=/bin/true" + - name: Unreachable when validation works + ansible.builtin.fail: + msg: system_baseline ran with an invalid system_baseline_apt_daily_timeout + rescue: + - name: The validation stopped the play + ansible.builtin.assert: + that: "'system_baseline_apt_daily_timeout must be' in ansible_failed_result.msg | default('')" + quiet: true + +# The journal cap is a number and a unit letter, or empty: a bare number (journald would read bytes), a zero, a space, a line break, a +# lower-case unit and a number that is not a string each stop the run before any change. +- name: A bad journal size cap is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_journal_max_use.yml + vars: + system_baseline_refused_journal: "{{ item }}" + loop: + - "300" + - "0" + - 10 M + - "10m" + - "200M\nStorage=none" + - 300 + +# A quote, a null item and a bare string (not a list) each stop the run: the bare string would otherwise be split into one-character +# patterns, and the null item would become an empty pattern that matches every package. +- name: A bad package blacklist is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_blacklist.yml + vars: + system_baseline_refused_blacklist: "{{ item }}" + loop: + - ['bad"name'] + - [null] + - linux-image-.* + +# Items that are not Debian package names (whitespace, null, empty, a trailing minus that apt reads as a removal, an option, upper case, a +# version pin), and a package that one input installs and another purges, each stop the run before any change. +# The overlaps are: an extra install against the profile's remove list (telnet), an extra install against an extra remove, and an extra +# remove against the profile's install list (tmux). +- name: A bad extra package list is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Refuse each bad value + ansible.builtin.include_tasks: tasks/refuse_extra_packages.yml + vars: + system_baseline_refused_case: "{{ item }}" + loop: + - { install: ['bad name'], expect: 'must be lists of package names' } + - { install: [null], expect: 'must be lists of package names' } + - { install: jq, expect: 'must be lists of package names' } + - { remove: [''], expect: 'must be lists of package names' } + - { install: ['jq-'], expect: 'must be lists of package names' } + - { install: ['-y'], expect: 'must be lists of package names' } + - { remove: ['Telnet'], expect: 'must be lists of package names' } + - { remove: ['ed=1.0'], expect: 'must be lists of package names' } + - { install: [telnet], expect: 'is both installed and purged' } + - { install: [jq], remove: [jq], expect: 'is both installed and purged' } + - { remove: [tmux], expect: 'is both installed and purged' } + +# The remaining plays only load the role's defaults (validate.yml changes nothing) and assert +# the resolved inputs. They cover the profiles converge.yml cannot run. +- name: The pve profile resolves + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + system_baseline_system_type: pve + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the pve profile + ansible.builtin.assert: + that: + - "'ufw' not in system_baseline_essential_packages" + - "'tmux' not in system_baseline_essential_packages" + - "'unattended-upgrades' in system_baseline_essential_packages" + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '03:00' + - system_baseline_secure_tmp_mounts == ['/dev/shm', '/tmp', '/var/tmp'] + - system_baseline_update + - system_baseline_apt_upgrade == 'dist' + - system_baseline_unattended_upgrade_origins | length == 3 + - system_baseline_unattended_upgrade_origins | select('search', 'Proxmox') | list == [] + - __system_baseline_install_packages == system_baseline_essential_packages + - __system_baseline_purge_packages == system_baseline_remove_packages + quiet: true + +- name: The ubuntu_vm profile resolves + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + system_baseline_system_type: ubuntu_vm + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the ubuntu_vm profile + ansible.builtin.assert: + that: + - "'qemu-guest-agent' in system_baseline_essential_packages" + - "'tmux' in system_baseline_essential_packages" + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == false + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' + - system_baseline_sysctl_hardening | selectattr('name', 'equalto', 'net.ipv4.conf.all.log_martians') | list | length == 1 + - system_baseline_apt_upgrade == 'safe' + - system_baseline_unattended_upgrade_origins == [] + - __system_baseline_install_packages == system_baseline_essential_packages + - __system_baseline_purge_packages == system_baseline_remove_packages + quiet: true + +# Consumer play vars override the profile. +- name: Consumer overrides win over the profile + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + system_baseline_system_type: ubuntu_vm + system_baseline_remove_packages: [telnet] + system_baseline_apt_upgrade: dist + system_baseline_profile_overrides: + ubuntu_vm: + unattended_upgrade_settings: + "Unattended-Upgrade::Automatic-Reboot": true + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the overrides + ansible.builtin.assert: + that: + - system_baseline_remove_packages == ['telnet'] + - system_baseline_apt_upgrade == 'dist' + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot'] == true + - system_baseline_unattended_upgrade_settings['Unattended-Upgrade::Automatic-Reboot-Time'] == '04:00' + - "'qemu-guest-agent' in system_baseline_essential_packages" + quiet: true + +# The extras append to the resolved lists, whether the profile's list or a flat input supplies them, and a name that is in both is listed once. +- name: Extra packages append to the resolved lists + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_essential_packages: [vim, curl] + system_baseline_extra_packages: [jq, vim, unattended-upgrades] + system_baseline_extra_remove_packages: [ed, telnet] + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the lists the role acts on + ansible.builtin.assert: + that: + - __system_baseline_install_packages == ['vim', 'curl', 'jq', 'unattended-upgrades'] + - "'ed' in __system_baseline_purge_packages" + - __system_baseline_purge_packages | select('equalto', 'telnet') | list | length == 1 + - system_baseline_remove_packages | difference(__system_baseline_purge_packages) | length == 0 + quiet: true + +# A flat input that is a plain string (the package module accepts one) still counts as a one-item list, with and without extras. +- name: A flat string package list still resolves + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + system_baseline_system_type: ubuntu_lxc + system_baseline_essential_packages: vim + system_baseline_extra_packages: [jq] + tasks: + - name: Load the role defaults + ansible.builtin.include_role: + name: mortis.kamino.system_baseline + tasks_from: validate.yml + public: true + - name: Assert the lists the role acts on + ansible.builtin.assert: + that: + - __system_baseline_install_packages == ['vim', 'jq'] + quiet: true + - name: Verify hosts: all gather_facts: false diff --git a/roles/systemd_hardening/molecule/default/converge.yml b/roles/systemd_hardening/molecule/default/converge.yml index c389edc..68c6ab7 100644 --- a/roles/systemd_hardening/molecule/default/converge.yml +++ b/roles/systemd_hardening/molecule/default/converge.yml @@ -12,91 +12,3 @@ LimitNOFILE: 1024 roles: - role: mortis.kamino.systemd_hardening - -# The plays below are refusals. The missing and unknown system types stop before the role -# changes anything. The malformed drop-in plays fail at dropins.yml, after the disable, mask -# and manager drop-in tasks ran, but those are no-ops after the converge above, so the -# idempotence run stays clean. A sentinel in the failure message tells "the role refused" -# from "the fail task after the role ran", which a bare rescue cannot. -- name: A run without systemd_hardening_system_type is refused - hosts: all - gather_facts: false - tasks: - - name: Apply the role without a system type - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.systemd_hardening - - name: Fail when the missing type was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The role refused the run - ansible.builtin.assert: - that: "'missing required arguments' in ansible_failed_result.msg | default('')" - quiet: true - -- name: An unknown system type is refused - hosts: all - gather_facts: false - vars: - systemd_hardening_system_type: not_a_type - tasks: - - name: Apply the role with an unknown type - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.systemd_hardening - - name: Fail when the unknown type was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The profile check stopped the play - ansible.builtin.assert: - that: "'is invalid' in ansible_failed_result.msg | default('')" - quiet: true - -- name: A drop-in entry that is not a mapping is refused - hosts: all - gather_facts: false - vars: - systemd_hardening_system_type: ubuntu_lxc - systemd_hardening_services: - testsvc: not-a-mapping - tasks: - - name: Apply the role with a malformed drop-in - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.systemd_hardening - - name: Fail when the malformed drop-in was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The drop-in validation stopped the play - ansible.builtin.assert: - that: "'must be a mapping' in ansible_failed_result.msg | default('')" - quiet: true - -- name: A drop-in list that is not a mapping is refused - hosts: all - gather_facts: false - vars: - systemd_hardening_system_type: ubuntu_lxc - systemd_hardening_services: [testsvc] - tasks: - - name: Apply the role with a list instead of a mapping - block: - - name: Include the role - ansible.builtin.include_role: - name: mortis.kamino.systemd_hardening - - name: Fail when the list was accepted - ansible.builtin.fail: - msg: MOLECULE-ACCEPTED - rescue: - - name: The role refused the run - ansible.builtin.assert: - that: - - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" - - "'systemd_hardening_services' in ansible_failed_result.msg | default('')" - quiet: true diff --git a/roles/systemd_hardening/molecule/default/verify.yml b/roles/systemd_hardening/molecule/default/verify.yml index 4348901..1d686c7 100644 --- a/roles/systemd_hardening/molecule/default/verify.yml +++ b/roles/systemd_hardening/molecule/default/verify.yml @@ -1,4 +1,99 @@ --- +# The refusals that stop before the role changes anything need no container, so they run once, +# on the controller, in check mode so that a refusal that regressed cannot change it. A sentinel +# in the failure message tells "the role refused" from "the fail task after the role ran", +# which a bare rescue cannot. +- name: A run without systemd_hardening_system_type is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + tasks: + - name: Apply the role without a system type + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the missing type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The role refused the run + ansible.builtin.assert: + that: "'missing required arguments' in ansible_failed_result.msg | default('')" + quiet: true + +- name: An unknown system type is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + systemd_hardening_system_type: not_a_type + tasks: + - name: Apply the role with an unknown type + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the unknown type was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The profile check stopped the play + ansible.builtin.assert: + that: "'is invalid' in ansible_failed_result.msg | default('')" + quiet: true + +- name: A drop-in list that is not a mapping is refused + hosts: localhost + connection: local + check_mode: true + gather_facts: false + vars: + systemd_hardening_system_type: ubuntu_lxc + systemd_hardening_services: [testsvc] + tasks: + - name: Apply the role with a list instead of a mapping + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the list was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The role refused the run + ansible.builtin.assert: + that: + - "'MOLECULE-ACCEPTED' not in ansible_failed_result.msg | default('')" + - "'systemd_hardening_services' in ansible_failed_result.msg | default('')" + quiet: true + +# This refusal comes at dropins.yml, after the disable, mask and manager drop-in tasks, so it +# runs on the container, where converge.yml already made those tasks no-ops. +- name: A drop-in entry that is not a mapping is refused + hosts: all + gather_facts: false + vars: + systemd_hardening_system_type: ubuntu_lxc + systemd_hardening_services: + testsvc: not-a-mapping + tasks: + - name: Apply the role with a malformed drop-in + block: + - name: Include the role + ansible.builtin.include_role: + name: mortis.kamino.systemd_hardening + - name: Fail when the malformed drop-in was accepted + ansible.builtin.fail: + msg: MOLECULE-ACCEPTED + rescue: + - name: The drop-in validation stopped the play + ansible.builtin.assert: + that: "'must be a mapping' in ansible_failed_result.msg | default('')" + quiet: true + # What the role is for: the installed risky units are disabled or masked, the manager # drop-in is in place, and the opt-in drop-in renders and is loaded by systemd. The # directives restate the converge vars, not the role's whole policy. From 7d11d23294ea2575b1a13716cbce5d4c0b96d1b9 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 15:20:18 +0000 Subject: [PATCH 25/26] ci: share a Molecule base config with prerun off and smart gathering Add .config/molecule/config.yml, which molecule merges under every scenario's molecule.yml. prerun is off: the CI wrapper already puts the checkout first on ANSIBLE_COLLECTIONS_PATH, so molecule's per-scenario reinstall of mortis.kamino into ANSIBLE_HOME is redundant. gathering is smart, so each host's facts are gathered once per playbook run instead of in every play. Add .config to build_ignore so scripts/check_tarball.py does not fail the build, and reword the Molecule rule and the two script comments that said molecule installs the collection into each scenario's ANSIBLE_HOME. Assisted-by: Claude Code:claude-opus-5-5 --- .config/molecule/config.yml | 9 +++++++++ .gitea/workflows/AGENTS.md | 7 ++++--- galaxy.yml | 1 + scripts/run_molecule_in_ci_image.sh | 4 ++-- scripts/run_molecule_scenarios.sh | 3 ++- 5 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 .config/molecule/config.yml diff --git a/.config/molecule/config.yml b/.config/molecule/config.yml new file mode 100644 index 0000000..573e2c3 --- /dev/null +++ b/.config/molecule/config.yml @@ -0,0 +1,9 @@ +--- +# Merged under every scenario's molecule.yml. prerun off: the CI wrapper puts this checkout +# first on ANSIBLE_COLLECTIONS_PATH, so molecule's per-scenario install is unused. +prerun: false +provisioner: + config_options: + defaults: + # Gather each host's facts once per playbook run, not in every play. + gathering: smart diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 9250962..6cba7ac 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -85,9 +85,10 @@ issue. - **A role named in an include, import, play `roles:` entry or meta dependency is written out in full**, never bare or templated. *Why:* the selector finds dependent roles by their FQCN. *Held:* control: a selector test fails a bare or templated name. -- **Scenarios load `mortis.kamino` from the checkout, never from molecule's installed copy, so - `galaxy.yml` is on IGNORED.** *Why:* molecule installs the collection from `galaxy.yml` into - each scenario's `ANSIBLE_HOME`, which is not on `ANSIBLE_COLLECTIONS_PATH`, so its changes +- **Scenarios load `mortis.kamino` from the checkout, never from an installed copy, so + `galaxy.yml` is on IGNORED.** *Why:* the checkout is first on `ANSIBLE_COLLECTIONS_PATH` and the + shared base config `.config/molecule/config.yml` turns off molecule's install of the collection + (`prerun: false`), so changes to `galaxy.yml` (release versions, `build_ignore`) do not change what a scenario runs, and the Build check proves the collection builds; they had caused about a third of full pull request runs and their minutes (#338). *Held:* control: `scripts/check_scenarios_load_checkout.py`, which diff --git a/galaxy.yml b/galaxy.yml index f930b4d..57eb7cb 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -39,6 +39,7 @@ build_ignore: - apm_modules - .apm-local - .claude + - .config - .gitea - .gitignore - .pre-commit-config.yaml diff --git a/scripts/run_molecule_in_ci_image.sh b/scripts/run_molecule_in_ci_image.sh index b471a24..9ffe9c8 100755 --- a/scripts/run_molecule_in_ci_image.sh +++ b/scripts/run_molecule_in_ci_image.sh @@ -29,8 +29,8 @@ else fi ansible --version molecule --version -# The collection under test first; molecule also installs it into each scenario's ANSIBLE_HOME, -# which the run script keeps in the job tree. +# The collection under test first; molecule does not install it again (prerun is off in +# .config/molecule/config.yml). export ANSIBLE_COLLECTIONS_PATH="$AC_ROOT:${extra_collections}/opt/collections" # Facts are not injected as variables (deprecated in ansible-core 2.22, removal scheduled for 2.24, see #364), so a # role that reads a bare `ansible_` fails its scenario here instead of in a consumer's inventory. diff --git a/scripts/run_molecule_scenarios.sh b/scripts/run_molecule_scenarios.sh index da915f8..a3fac0a 100755 --- a/scripts/run_molecule_scenarios.sh +++ b/scripts/run_molecule_scenarios.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # 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 -# // (molecule reinstalls the collection there with --force). Exit 1 on a failure. +# // (no collection is installed there: .config/molecule/config.yml sets prerun false). +# Exit 1 on a failure. # # scripts/run_molecule_scenarios.sh < scenario-dirs set -euo pipefail From 380d52cd13194156c06aab39583aeb3c182cddf4 Mon Sep 17 00:00:00 2001 From: Defame1297 Date: Fri, 27 Nov 2026 15:44:34 +0000 Subject: [PATCH 26/26] ci: turn on Ansible pipelining for Molecule scenarios Set connection.pipelining in the shared Molecule base config. Without it, every remote task over the community.docker.docker connection pays extra docker exec and docker cp calls to create a temp dir, copy the module in and clean up; with it, the module goes over stdin. The docker connection declares has_pipelining and has no pipelining option of its own, so core's global setting applies. No role or image sets requiretty. Closes #423 Assisted-by: Claude Code:claude-opus-5-5 --- .config/molecule/config.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.config/molecule/config.yml b/.config/molecule/config.yml index 573e2c3..4ea9b37 100644 --- a/.config/molecule/config.yml +++ b/.config/molecule/config.yml @@ -4,6 +4,10 @@ prerun: false provisioner: config_options: + connection: + # Pipe each module over stdin: without it every task pays extra docker exec and docker cp + # calls to make a temp dir, copy the module in and clean up. + pipelining: true defaults: # Gather each host's facts once per playbook run, not in every play. gathering: smart