diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 44317c6..685802d 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -96,7 +96,9 @@ issue. 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 `run_molecule_in_ci_image.sh` runs on the selected scenarios before they start, fails the run - when the environment molecule gives `ansible-playbook` resolves `mortis.kamino` anywhere else. + when the environment molecule gives `ansible-playbook` resolves `mortis.kamino` anywhere else, + or when `prerun` is not off once the base config is merged as molecule's CLI merges it (a + scenario turns it on, or the base config is moved or turns it on). A pull request that selects no scenario runs no check; the next one that does, and the nightly run, catch a change that broke the rule. - **A new file outside `roles//` runs every scenario until it is added to IGNORED, and it diff --git a/changelogs/fragments/478-ufw-fail2ban-check-mode.yml b/changelogs/fragments/478-ufw-fail2ban-check-mode.yml new file mode 100644 index 0000000..6e57dbc --- /dev/null +++ b/changelogs/fragments/478-ufw-fail2ban-check-mode.yml @@ -0,0 +1,9 @@ +--- +bugfixes: + - >- + ufw - ``--check`` no longer fails on a host where ufw is not installed yet; the preview reports + the install and skips the tasks that need the ``ufw`` binary. + - >- + fail2ban - ``--check`` no longer fails on a host where fail2ban is not installed yet, through + either entry point; the preview reports the install and skips the configuration, service and + jail tasks. 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 3e58423..4e73994 100644 --- a/docs/adr/0002-self-built-ci-and-molecule-images.md +++ b/docs/adr/0002-self-built-ci-and-molecule-images.md @@ -12,7 +12,8 @@ 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). + [ADR 0003](0003-molecule-controller-image.md) adds a `molecule-controller` image to this set, + which Molecule pins instead of `ci`. - **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/AGENTS.md b/docs/adr/AGENTS.md index d90f92b..44581cf 100644 --- a/docs/adr/AGENTS.md +++ b/docs/adr/AGENTS.md @@ -11,6 +11,10 @@ the author sees the change before it merges; aspirational means nothing checks i - **Status is `accepted` or `superseded by NNNN`, nothing else.** A proposal lives in an issue or a pull request and is never committed as "proposed". *Why:* a committed ADR is either in force or replaced; a draft in the tree reads as a decision. *Held:* review. +- **When a later ADR changes part of an earlier one, the earlier one stays `accepted` and as + decided, except for one sentence beside that part naming the later ADR and what it changes;** + the later ADR names the earlier one in its Context. *Why:* neither status fits a partial change, + and a reader of the earlier ADR learns which part no longer holds and where it went. *Held:* review. - **An ADR is accepted on the maintainer's approval of its pull request, which sets status `accepted`.** *Why:* an ADR binds every contributor, so the maintainer decides it. *Held:* control: the `CODEOWNERS` entry for `docs/adr/`, which requires the maintainer's code-owner diff --git a/roles/fail2ban/README.md b/roles/fail2ban/README.md index 35d658c..8ce1978 100644 --- a/roles/fail2ban/README.md +++ b/roles/fail2ban/README.md @@ -89,17 +89,19 @@ The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_ - Verify checks that the `sshd` jail does not read `/var/log/auth.log`, that `jail.local` holds the configured `ignoreip` in `[DEFAULT]` and none of the refused values, that each service jail has its own `jail.d` file and the refused one left no file, that `fail2ban-client -t` passes, and that the running daemon loaded `sshd`, `svc-a` and `svc-b` and applies the `ignoreip` network to both a base jail and a service jail. - The side effect bans an address and rewrites `jail.local` with a new `maxretry`; verify checks the new value is active, the ban is still in force and the daemon PID is unchanged, so the change reloaded Fail2Ban instead of restarting it. +The scenario `molecule/check-absent/` runs on the same two platforms: prepare purges fail2ban and refreshes the APT cache, then `check` runs the main entry point and `service_jail` under `--check`, which must pass with fail2ban not installed. Nothing is applied. + Not covered: no failure is sent through a jail, so a ban triggered by `failregex` is not tested, and the reload behaviours read from the Fail2Ban source (see Notes) are not run. ## Notes - Idempotent: yes. -- Check mode: `--check` previews a host where fail2ban is already installed; a play-level `check_mode: true` is not supported. On a host without fail2ban it fails at the configuration and service tasks: the package is not installed under `--check`, so `/etc/fail2ban`, `fail2ban-client` and the unit are missing. +- Check mode: `--check` is the supported preview; a play-level `check_mode: true` is not supported. On a host without fail2ban the preview reports the install and skips the configuration, the service and the jail tasks, which need `/etc/fail2ban`, `fail2ban-client` and the unit. - `fail2ban_ignoreip` lives in the `[DEFAULT]` section of `jail.local`, so it also applies to the jails that `service_jail` writes to `jail.d`. The exemption only exists once the main entry point has written `jail.local` on that host: `service_jail` does not read `fail2ban_ignoreip`, so a host that uses only `service_jail` has none. - `fail2ban_ignoreip` replaces an `ignoreip` set in `jail.conf` or `jail.d/*.conf`, which Fail2Ban reads before `jail.local`; a `jail.d/*.local` file is read after it and can still override it for one jail. Entries must not contain whitespace, `;` or `%` (a `;` after whitespace starts a comment in Fail2Ban's config files and a `%` is interpolation syntax). - Prefer IP addresses and CIDR networks in `fail2ban_ignoreip`. Fail2Ban resolves a hostname when the jail starts, and a failed lookup leaves that entry ineffective with only a log warning. The validation of `fail2ban_ignoreip` runs under the `fail2ban_validate` tag, so `--tags fail2ban_configure` skips it. - Changing `jail.local` or a service jail reloads Fail2Ban instead of restarting it. A restart stops every jail, which flushes its bans out of the firewall until they are restored from the database, and forgets failures counted toward `maxretry`; a reload applies the new settings to the running jails. When the whole role runs, the reload comes after `fail2ban-client -t`. - What a reload does not do, compared with the restart it replaces (read from the Fail2Ban 1.1.0 source, not run here): it does not unban an address that a widened `fail2ban_ignoreip` now covers (only a restart skips ignored addresses when it restores bans, so run `fail2ban-client unban
` to release one at once, or wait for the ban to expire); it does not change bans that already exist when `bantime` changes; and it does not apply server-level settings (`loglevel`, `dbfile`, `socket`, `pidfile`), which this role does not write. A changed `backend` restarts that jail by itself. - With `--tags fail2ban_configure` only, `fail2ban-client -t` does not run before the reload; the reload (`fail2ban-client reload` in the upstream unit) still rejects a bad configuration and leaves the running daemon alone. -- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode. +- `fail2ban-client -t` runs on every invocation of both entry points, not only when a file changed, so a broken file fails every run until fixed. It also runs in check mode, except on a host without fail2ban. - `no_log` is not used: the role handles no secrets. diff --git a/roles/fail2ban/handlers/main.yml b/roles/fail2ban/handlers/main.yml index a5dd89b..5606559 100644 --- a/roles/fail2ban/handlers/main.yml +++ b/roles/fail2ban/handlers/main.yml @@ -11,3 +11,5 @@ ansible.builtin.systemd: name: fail2ban state: reloaded + # Under --check on a fresh host the package is not installed, so there is no unit to reload. + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed diff --git a/roles/fail2ban/molecule/check-absent/converge.yml b/roles/fail2ban/molecule/check-absent/converge.yml new file mode 100644 index 0000000..fe6d800 --- /dev/null +++ b/roles/fail2ban/molecule/check-absent/converge.yml @@ -0,0 +1,21 @@ +--- +# Run only under --check (the check step): fail2ban is not installed, so the tasks that need it skip. +- name: Converge the base role on a host without fail2ban + hosts: all + roles: + - role: mortis.kamino.fail2ban + +- name: Converge a service jail on a host without fail2ban + hosts: all + tasks: + - name: Service jail with a journalmatch + ansible.builtin.include_role: + name: mortis.kamino.fail2ban + tasks_from: service_jail + vars: + fail2ban_service_name: svc-a + fail2ban_service_jail: + port: "8080" + journalmatch: "_SYSTEMD_UNIT=ssh.service" + fail2ban_service_filter: + failregex: "^.*denied for .*$" diff --git a/roles/fail2ban/molecule/check-absent/molecule.yml b/roles/fail2ban/molecule/check-absent/molecule.yml new file mode 100644 index 0000000..1ddf898 --- /dev/null +++ b/roles/fail2ban/molecule/check-absent/molecule.yml @@ -0,0 +1,55 @@ +--- +# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 +# (MOLECULE_IMAGE) and molecule-ubuntu2604 (MOLECULE_IMAGE_2604) images, pinned in +# .gitea/workflows/molecule.yml. No privileged mode: systemd needs a writable cgroup and the +# firewall tools need NET_ADMIN, nothing else. Needs the network: +# prepare purges the fail2ban the image ships and refreshes the APT cache the image deletes. +driver: + name: docker +platforms: + - name: ${KAMINO_RUN_ID:-local}-fail2ban-check-absent-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined + - name: ${KAMINO_RUN_ID:-local}-fail2ban-check-absent-2604-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE_2604} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined +provisioner: + name: ansible +verifier: + name: ansible +scenario: + # Previews the role on a host without fail2ban (--check only, nothing is applied); no destroy: + # scripts/run_molecule_scenarios.sh removes the container as soon as this scenario ends. + test_sequence: + - dependency + - create + - prepare + - check diff --git a/roles/fail2ban/molecule/check-absent/prepare.yml b/roles/fail2ban/molecule/check-absent/prepare.yml new file mode 100644 index 0000000..7e599de --- /dev/null +++ b/roles/fail2ban/molecule/check-absent/prepare.yml @@ -0,0 +1,16 @@ +--- +# The image ships fail2ban and no APT lists; the check step needs fail2ban gone and the lists back, +# or the install task cannot even preview the package. +- name: Prepare a host without fail2ban + hosts: all + gather_facts: false + tasks: + - name: Purge fail2ban + ansible.builtin.apt: + name: fail2ban + state: absent + purge: true + + - name: Refresh the APT cache + ansible.builtin.apt: + update_cache: true diff --git a/roles/fail2ban/tasks/configure.yml b/roles/fail2ban/tasks/configure.yml index fd635e5..317a84a 100644 --- a/roles/fail2ban/tasks/configure.yml +++ b/roles/fail2ban/tasks/configure.yml @@ -8,3 +8,5 @@ group: root mode: "0600" notify: Reload Fail2Ban + # Under --check on a fresh host the package is not installed, so /etc/fail2ban is missing. + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed diff --git a/roles/fail2ban/tasks/install.yml b/roles/fail2ban/tasks/install.yml index 776ba78..7b0940f 100644 --- a/roles/fail2ban/tasks/install.yml +++ b/roles/fail2ban/tasks/install.yml @@ -7,3 +7,4 @@ # Required for `backend = systemd` jails (journalmatch), e.g. gitea's. - python3-systemd state: present + register: __fail2ban_install diff --git a/roles/fail2ban/tasks/service.yml b/roles/fail2ban/tasks/service.yml index 8244fd6..d10a854 100644 --- a/roles/fail2ban/tasks/service.yml +++ b/roles/fail2ban/tasks/service.yml @@ -8,6 +8,8 @@ failed_when: fail2ban_test.rc != 0 changed_when: false check_mode: false + # Under --check on a fresh host the package is not installed: no fail2ban-client and no unit. + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed - name: Ensure Fail2Ban service is running become: true @@ -15,6 +17,7 @@ name: fail2ban enabled: "{{ fail2ban_service.enabled | default(true) }}" state: "{{ fail2ban_service.state | default('started') }}" + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed # Handlers run at the end of the play; flush so the reload happens after the # configuration test above and before the jail check below. @@ -33,4 +36,6 @@ delay: 2 changed_when: false check_mode: false - when: fail2ban_service.state | default('started') == 'started' + when: + - not ansible_check_mode or __fail2ban_install | default({}) is not changed + - fail2ban_service.state | default('started') == 'started' diff --git a/roles/fail2ban/tasks/service_jail.yml b/roles/fail2ban/tasks/service_jail.yml index c866576..2fd3dd1 100644 --- a/roles/fail2ban/tasks/service_jail.yml +++ b/roles/fail2ban/tasks/service_jail.yml @@ -33,6 +33,8 @@ group: root mode: "0644" notify: Reload Fail2Ban + # Under --check on a fresh host the package is not installed, so /etc/fail2ban is missing. + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed tags: [fail2ban, fail2ban_service_jail] - name: Deploy service jail @@ -44,14 +46,15 @@ group: root mode: "0644" notify: Reload Fail2Ban + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed + tags: [fail2ban, fail2ban_service_jail] # Read-only, so it also runs in check mode. A failure leaves the broken file on # disk and fails every run until fixed, instead of only the run that wrote it. - tags: [fail2ban, fail2ban_service_jail] - - name: Test Fail2Ban configuration become: true ansible.builtin.command: fail2ban-client -t changed_when: false check_mode: false + when: not ansible_check_mode or __fail2ban_install | default({}) is not changed tags: [fail2ban, fail2ban_service_jail] diff --git a/roles/ufw/README.md b/roles/ufw/README.md index 811f928..1fd6bc1 100644 --- a/roles/ufw/README.md +++ b/roles/ufw/README.md @@ -145,6 +145,8 @@ The scenario `molecule/default/` runs in CI only, on two platforms: `${MOLECULE_ - Verify checks `before.rules`: the loopback accept, the INVALID-state drop behind its logging rule and in its place among the input rules. - Verify runs `service_rules` under the `check_mode` keyword and checks that the rule list did not change. +The scenario `molecule/check-absent/` runs on the same two platforms: prepare purges ufw and refreshes the APT cache, then `check` runs the main entry point and `service_rules` under `--check`, which must pass with ufw not installed. Nothing is applied. + Not covered: `ufw_before_rules` entries and `ufw_sysctl_overrides` are never set, and `orphan_rules` runs in check mode only under `--check` (the `check` steps), not under the `check_mode` keyword. ## Notes @@ -156,5 +158,5 @@ Not covered: `ufw_before_rules` entries and `ufw_sysctl_overrides` are never set - Rule schema is asserted before anything changes: `rule` must be allow, deny, reject or limit, `port` a positive integer, `proto` tcp or udp, and each rule needs `port`, `from`, `to` or `interface`. - UFW is only re-enabled when `ufw status verbose` shows it inactive or the logging line differs, because the module rewrites rules and re-applies sysctl on every call. - The `Reload UFW` handler runs `ufw reload`. -- Check mode: `--check` previews a host where ufw is already installed; a play-level `check_mode: true` is not supported. On a host without ufw it fails at the default policy tasks: the package is not installed under `--check`, and the module needs the `ufw` binary. +- Check mode: `--check` is the supported preview; a play-level `check_mode: true` is not supported. On a host without ufw the preview reports the install and skips the configuration (`before.rules`, default policies, rules, enable), which needs the `ufw` binary. - `no_log` is not used: the role handles no secrets. diff --git a/roles/ufw/molecule/check-absent/converge.yml b/roles/ufw/molecule/check-absent/converge.yml new file mode 100644 index 0000000..8b9c139 --- /dev/null +++ b/roles/ufw/molecule/check-absent/converge.yml @@ -0,0 +1,26 @@ +--- +# Run only under --check (the check step): ufw is not installed, so the tasks that need it skip. +- name: Converge on a host without ufw + hosts: all + # The role reads no facts; ufw_ssh_port defaults from ansible_port. + gather_facts: false + roles: + - role: mortis.kamino.ufw + vars: + ufw_rules: + - {rule: allow, port: 22, proto: tcp, comment: ssh} + - {rule: allow, port: 8080, proto: tcp, comment: web} + +# The entry point a service role calls: its `ufw status` read fails on this host, so it must skip. +- name: Converge the rules of a service on a host without ufw + hosts: all + gather_facts: false + tasks: + - name: Rules of one service through the entry point + ansible.builtin.include_role: + name: mortis.kamino.ufw + tasks_from: service_rules + vars: + ufw_service_name: svc_a + ufw_service_rules: + - {rule: allow, port: 8001, proto: tcp, comment: alpha web} diff --git a/roles/ufw/molecule/check-absent/molecule.yml b/roles/ufw/molecule/check-absent/molecule.yml new file mode 100644 index 0000000..1ca88cf --- /dev/null +++ b/roles/ufw/molecule/check-absent/molecule.yml @@ -0,0 +1,55 @@ +--- +# Runs on the repository's own runner (label kamino-molecule), in the molecule-ubuntu2404 +# (MOLECULE_IMAGE) and molecule-ubuntu2604 (MOLECULE_IMAGE_2604) images, pinned in +# .gitea/workflows/molecule.yml. No privileged mode: systemd needs a writable cgroup and the +# firewall tools need NET_ADMIN, nothing else. Needs the network: +# prepare purges the ufw the image ships and refreshes the APT cache the image deletes. +driver: + name: docker +platforms: + - name: ${KAMINO_RUN_ID:-local}-ufw-check-absent-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined + - name: ${KAMINO_RUN_ID:-local}-ufw-check-absent-2604-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" + image: ${MOLECULE_IMAGE_2604} + pre_build_image: true + pull: true + command: /sbin/init + cgroupns_mode: host + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + tmpfs: + - /run + - /run/lock + capabilities: + - NET_ADMIN + security_opts: + - apparmor=unconfined +provisioner: + name: ansible +verifier: + name: ansible +scenario: + # Previews the role on a host without ufw (--check only, nothing is applied); no destroy: + # scripts/run_molecule_scenarios.sh removes the container as soon as this scenario ends. + test_sequence: + - dependency + - create + - prepare + - check diff --git a/roles/ufw/molecule/check-absent/prepare.yml b/roles/ufw/molecule/check-absent/prepare.yml new file mode 100644 index 0000000..6c98ec3 --- /dev/null +++ b/roles/ufw/molecule/check-absent/prepare.yml @@ -0,0 +1,16 @@ +--- +# The image ships ufw and no APT lists; the check step needs ufw gone and the lists back, or the +# install task cannot even preview the package. +- name: Prepare a host without ufw + hosts: all + gather_facts: false + tasks: + - name: Purge ufw + ansible.builtin.apt: + name: ufw + state: absent + purge: true + + - name: Refresh the APT cache + ansible.builtin.apt: + update_cache: true diff --git a/roles/ufw/tasks/before_rules.yml b/roles/ufw/tasks/before_rules.yml index 2da14ed..f1aa5ca 100644 --- a/roles/ufw/tasks/before_rules.yml +++ b/roles/ufw/tasks/before_rules.yml @@ -8,7 +8,9 @@ group: root mode: "0644" notify: Reload UFW - when: ufw_enabled + when: + - ufw_enabled + - __ufw_can_configure | default(true) # Not gated on ufw_aggregated_before_rules being non-empty: this template # fully replaces the stock before.rules (unlike rules.yml, which only adds # to it), and its unconditional loopback-ACCEPT block must always be diff --git a/roles/ufw/tasks/defaults.yml b/roles/ufw/tasks/defaults.yml index db659d1..4420cb9 100644 --- a/roles/ufw/tasks/defaults.yml +++ b/roles/ufw/tasks/defaults.yml @@ -4,18 +4,24 @@ community.general.ufw: direction: incoming policy: "{{ ufw_defaults.incoming }}" - when: ufw_enabled + when: + - ufw_enabled + - __ufw_can_configure | default(true) - name: Set default outgoing policy become: true community.general.ufw: direction: outgoing policy: "{{ ufw_defaults.outgoing }}" - when: ufw_enabled + when: + - ufw_enabled + - __ufw_can_configure | default(true) - name: Set default routed policy become: true community.general.ufw: direction: routed policy: "{{ ufw_defaults.routed }}" - when: ufw_enabled + when: + - ufw_enabled + - __ufw_can_configure | default(true) diff --git a/roles/ufw/tasks/enable.yml b/roles/ufw/tasks/enable.yml index e346da3..12df62d 100644 --- a/roles/ufw/tasks/enable.yml +++ b/roles/ufw/tasks/enable.yml @@ -11,7 +11,9 @@ environment: LC_ALL: C LANGUAGE: C - when: ufw_enabled + when: + - ufw_enabled + - __ufw_can_configure | default(true) - name: Enable UFW become: true @@ -26,6 +28,7 @@ else 'Logging: on (' ~ ufw_logging ~ ')' }} when: - ufw_enabled + - __ufw_can_configure | default(true) - >- 'Status: active' not in ufw_status_verbose.stdout or ufw_logging_expected not in ufw_status_verbose.stdout diff --git a/roles/ufw/tasks/install.yml b/roles/ufw/tasks/install.yml index 606a728..bb0d2a3 100644 --- a/roles/ufw/tasks/install.yml +++ b/roles/ufw/tasks/install.yml @@ -4,3 +4,17 @@ ansible.builtin.package: name: "{{ ufw_package_name }}" state: present + register: __ufw_install + +# ansible_check_mode is not used: the play-level `check_mode: true` keyword does not set it inside +# include_role tasks. A command task is skipped in both forms, the same probe as tasks/sysctl.yml. +- name: Probe whether the run is in check mode + ansible.builtin.command: "true" + register: __ufw_install_probe + changed_when: false + +# False only when a check-mode run would install ufw: the binary and /etc/ufw are then missing. +# Undefined when this file's tags are skipped; the guards then default it to true. +- name: Remember whether ufw can be configured + ansible.builtin.set_fact: + __ufw_can_configure: "{{ __ufw_install is not changed or __ufw_install_probe is not skipped }}" diff --git a/roles/ufw/tasks/rules.yml b/roles/ufw/tasks/rules.yml index 61b1007..ac3a822 100644 --- a/roles/ufw/tasks/rules.yml +++ b/roles/ufw/tasks/rules.yml @@ -23,3 +23,4 @@ when: - ufw_enabled - ufw_manage_rules + - __ufw_can_configure | default(true) diff --git a/scripts/check_scenarios_load_checkout.py b/scripts/check_scenarios_load_checkout.py index 9bad4d8..097a497 100644 --- a/scripts/check_scenarios_load_checkout.py +++ b/scripts/check_scenarios_load_checkout.py @@ -5,8 +5,10 @@ python3 -I scripts/check_scenarios_load_checkout.py < scenario-dirs Checks the environment molecule hands ansible-playbook, not only the inherited one: a scenario's -own env can change it. The rule it holds is in .gitea/workflows/AGENTS.md (Molecule). Exit 1 when -a scenario would load another copy, or none. +own env can change it. Also checks that molecule's prerun, its install of the collection, is off +once the base config is merged as molecule's CLI merges it. The rule it holds is in +.gitea/workflows/AGENTS.md (Molecule). Exit 1 when a scenario would load another copy, or none, +or has prerun on. """ import json @@ -16,6 +18,8 @@ import sys import tempfile from molecule.config import Config +from molecule.shell import LOCAL_CONFIG_SEARCH +from molecule.util import lookup_config_file CHECKOUT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) RULE = ( @@ -23,20 +27,25 @@ RULE = ( " copy: the scenario selector ignores galaxy.yml on that rule" " (.gitea/workflows/AGENTS.md, Molecule)" ) +PRERUN = ( + "prerun must be off, so molecule does not install mortis.kamino again: set `prerun: false`" + " in the base config {base} and do not turn it on in the scenario (.gitea/workflows/AGENTS.md, Molecule)" +) -def playbook_env(scenario): - """The environment molecule gives ansible-playbook in `scenario`, as a role scenario runs it.""" +def scenario_config(scenario): + """Molecule's config of `scenario` as `molecule converge` builds it there, and its base config.""" parts = scenario.split("/") cwd = os.path.join(CHECKOUT, *parts[:2]) if parts[0] == "roles" else CHECKOUT - # molecule takes the project from the working directory; each call sets it afresh + # molecule takes the project and the base config from the working directory; set it afresh os.chdir(cwd) + base = lookup_config_file(LOCAL_CONFIG_SEARCH) config = Config( os.path.relpath(os.path.join(CHECKOUT, scenario, "molecule.yml")), - args={}, + args={"base_config": [base] if base else []}, command_args={"subcommand": "converge"}, ) - return dict(config.provisioner.env) + return config, base def collection_paths(env, cwd): @@ -79,8 +88,16 @@ def main(): os.environ.setdefault("ANSIBLE_HOME", home) for scenario in filter(None, sys.stdin.read().splitlines()): scenario_dir = os.path.join(CHECKOUT, scenario) + config, base = scenario_config(scenario) + # molecule's worker reads this key to decide whether to install the collection + if config.config_data["prerun"] is not False: + failed = True + base = ( + base or os.path.join(CHECKOUT, LOCAL_CONFIG_SEARCH) + " (not found)" + ) + print(f"::error::{scenario}: " + PRERUN.format(base=base)) paths = [os.path.join(scenario_dir, "collections")] - paths += collection_paths(playbook_env(scenario), scenario_dir) + paths += collection_paths(dict(config.provisioner.env), scenario_dir) found = loaded_copy(paths) if found and os.path.realpath(found) == CHECKOUT: continue diff --git a/scripts/run_molecule_in_ci_image.sh b/scripts/run_molecule_in_ci_image.sh index 9ffe9c8..4de5037 100755 --- a/scripts/run_molecule_in_ci_image.sh +++ b/scripts/run_molecule_in_ci_image.sh @@ -30,7 +30,7 @@ fi ansible --version molecule --version # The collection under test first; molecule does not install it again (prerun is off in -# .config/molecule/config.yml). +# .config/molecule/config.yml, which check_scenarios_load_checkout.py holds). 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/tests/scripts/test_check_scenarios_load_checkout.py b/tests/scripts/test_check_scenarios_load_checkout.py index 1aec799..03f2f05 100644 --- a/tests/scripts/test_check_scenarios_load_checkout.py +++ b/tests/scripts/test_check_scenarios_load_checkout.py @@ -43,6 +43,11 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase): self.ac_root = self.tmp / "ac" self.checkout = collection(self.ac_root) (self.checkout / "scripts").mkdir() + # molecule's CLI finds the base config from the repository root, as in the real checkout + subprocess.run(["git", "init", "-q", str(self.checkout)], check=True) + self.base_config = self.checkout / ".config" / "molecule" / "config.yml" + self.base_config.parent.mkdir(parents=True) + self.base_config.write_text("prerun: false\n") shutil.copy(SCRIPT, self.checkout / "scripts") self.other = self.tmp / "other" collection(self.other) @@ -55,10 +60,14 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase): "ANSIBLE_COLLECTIONS_PATH": f"{self.ac_root}:{self.other}", } - def scenario(self, path, env=None): + def scenario(self, path, env=None, **keys): d = self.checkout / path d.mkdir(parents=True, exist_ok=True) - config = {"driver": {"name": "default"}, "platforms": [{"name": "instance"}]} + config = { + "driver": {"name": "default"}, + "platforms": [{"name": "instance"}], + **keys, + } if env: config["provisioner"] = {"name": "ansible", "env": env} (d / "molecule.yml").write_text(yaml.safe_dump(config)) @@ -81,7 +90,14 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase): self.assertIn("must load mortis.kamino from the checkout", result.stdout) self.assertIn(found, result.stdout) + def assert_prerun_refused(self, result, scenario="roles/alpha/molecule/default"): + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) + self.assertIn(f"::error::{scenario}: ", result.stdout) + self.assertIn("prerun", result.stdout) + self.assertIn(".config/molecule/config.yml", result.stdout) + def test_the_checkout_first_passes(self): + # the scenarios inherit prerun off from the base config result = self.run_check( "roles/alpha/molecule/default\nextensions/molecule/image-smoke\n" ) @@ -120,6 +136,18 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase): self.assert_refused(result, "extensions/molecule/image-smoke") self.assertNotIn("roles/alpha/molecule/default", result.stdout) + def test_a_scenario_with_prerun_on_fails(self): + self.scenario("roles/alpha/molecule/default", prerun=True) + self.assert_prerun_refused(self.run_check()) + + def test_a_missing_base_config_fails(self): + self.base_config.unlink() + self.assert_prerun_refused(self.run_check()) + + def test_a_base_config_with_prerun_on_fails(self): + self.base_config.write_text("prerun: true\n") + self.assert_prerun_refused(self.run_check()) + if __name__ == "__main__": unittest.main()