Merge branch 'main' into ci/477-molecule-controller-image
Build / build (pull_request) Successful in 29s
Lint / lint (pull_request) Successful in 3m21s
Molecule / molecule (pull_request) Successful in 32m9s

This commit is contained in:
Defame1297 committed 2026-11-29 18:19:41 +00:00
commit 1289da3104
25 files changed
+317 -24

No files matched your search

+3 -1
View File
@@ -96,7 +96,9 @@ issue.
proves the collection builds; they had caused about a third of full pull request runs and their 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 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 `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 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. run, catch a change that broke the rule.
- **A new file outside `roles/<role>/` runs every scenario until it is added to IGNORED, and it - **A new file outside `roles/<role>/` runs every scenario until it is added to IGNORED, and it
@@ -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.
@@ -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 - **We build our own images:** a `ci` image, and one Dockerfile per molecule image (one per Ubuntu
release, and later the Debian 13 one). 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 - **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 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 downloaded, because that install path is what the test exercises. A converge is not kept off
+4
View File
@@ -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 - **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 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. 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 - **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:* `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 control: the `CODEOWNERS` entry for `docs/adr/`, which requires the maintainer's code-owner
+4 -2
View File
@@ -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. - 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 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. 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 ## Notes
- Idempotent: yes. - 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` 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). - `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. - 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`. - 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 <address>` 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. - 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 <address>` 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. - 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. - `no_log` is not used: the role handles no secrets.
+2
View File
@@ -11,3 +11,5 @@
ansible.builtin.systemd: ansible.builtin.systemd:
name: fail2ban name: fail2ban
state: reloaded 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
@@ -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 <HOST>.*$"
@@ -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
@@ -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
+2
View File
@@ -8,3 +8,5 @@
group: root group: root
mode: "0600" mode: "0600"
notify: Reload Fail2Ban 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
+1
View File
@@ -7,3 +7,4 @@
# Required for `backend = systemd` jails (journalmatch), e.g. gitea's. # Required for `backend = systemd` jails (journalmatch), e.g. gitea's.
- python3-systemd - python3-systemd
state: present state: present
register: __fail2ban_install
+6 -1
View File
@@ -8,6 +8,8 @@
failed_when: fail2ban_test.rc != 0 failed_when: fail2ban_test.rc != 0
changed_when: false changed_when: false
check_mode: 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 - name: Ensure Fail2Ban service is running
become: true become: true
@@ -15,6 +17,7 @@
name: fail2ban name: fail2ban
enabled: "{{ fail2ban_service.enabled | default(true) }}" enabled: "{{ fail2ban_service.enabled | default(true) }}"
state: "{{ fail2ban_service.state | default('started') }}" 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 # Handlers run at the end of the play; flush so the reload happens after the
# configuration test above and before the jail check below. # configuration test above and before the jail check below.
@@ -33,4 +36,6 @@
delay: 2 delay: 2
changed_when: false changed_when: false
check_mode: 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'
+5 -2
View File
@@ -33,6 +33,8 @@
group: root group: root
mode: "0644" mode: "0644"
notify: Reload Fail2Ban 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] tags: [fail2ban, fail2ban_service_jail]
- name: Deploy service jail - name: Deploy service jail
@@ -44,14 +46,15 @@
group: root group: root
mode: "0644" mode: "0644"
notify: Reload Fail2Ban 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 # 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. # disk and fails every run until fixed, instead of only the run that wrote it.
tags: [fail2ban, fail2ban_service_jail]
- name: Test Fail2Ban configuration - name: Test Fail2Ban configuration
become: true become: true
ansible.builtin.command: fail2ban-client -t ansible.builtin.command: fail2ban-client -t
changed_when: false changed_when: false
check_mode: false check_mode: false
when: not ansible_check_mode or __fail2ban_install | default({}) is not changed
tags: [fail2ban, fail2ban_service_jail] tags: [fail2ban, fail2ban_service_jail]
+3 -1
View File
@@ -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 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. - 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. 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 ## 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`. - 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. - 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`. - 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. - `no_log` is not used: the role handles no secrets.
@@ -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}
@@ -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
@@ -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
+3 -1
View File
@@ -8,7 +8,9 @@
group: root group: root
mode: "0644" mode: "0644"
notify: Reload UFW 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 # Not gated on ufw_aggregated_before_rules being non-empty: this template
# fully replaces the stock before.rules (unlike rules.yml, which only adds # fully replaces the stock before.rules (unlike rules.yml, which only adds
# to it), and its unconditional loopback-ACCEPT block must always be # to it), and its unconditional loopback-ACCEPT block must always be
+9 -3
View File
@@ -4,18 +4,24 @@
community.general.ufw: community.general.ufw:
direction: incoming direction: incoming
policy: "{{ ufw_defaults.incoming }}" policy: "{{ ufw_defaults.incoming }}"
when: ufw_enabled when:
- ufw_enabled
- __ufw_can_configure | default(true)
- name: Set default outgoing policy - name: Set default outgoing policy
become: true become: true
community.general.ufw: community.general.ufw:
direction: outgoing direction: outgoing
policy: "{{ ufw_defaults.outgoing }}" policy: "{{ ufw_defaults.outgoing }}"
when: ufw_enabled when:
- ufw_enabled
- __ufw_can_configure | default(true)
- name: Set default routed policy - name: Set default routed policy
become: true become: true
community.general.ufw: community.general.ufw:
direction: routed direction: routed
policy: "{{ ufw_defaults.routed }}" policy: "{{ ufw_defaults.routed }}"
when: ufw_enabled when:
- ufw_enabled
- __ufw_can_configure | default(true)
+4 -1
View File
@@ -11,7 +11,9 @@
environment: environment:
LC_ALL: C LC_ALL: C
LANGUAGE: C LANGUAGE: C
when: ufw_enabled when:
- ufw_enabled
- __ufw_can_configure | default(true)
- name: Enable UFW - name: Enable UFW
become: true become: true
@@ -26,6 +28,7 @@
else 'Logging: on (' ~ ufw_logging ~ ')' }} else 'Logging: on (' ~ ufw_logging ~ ')' }}
when: when:
- ufw_enabled - ufw_enabled
- __ufw_can_configure | default(true)
- >- - >-
'Status: active' not in ufw_status_verbose.stdout 'Status: active' not in ufw_status_verbose.stdout
or ufw_logging_expected not in ufw_status_verbose.stdout or ufw_logging_expected not in ufw_status_verbose.stdout
+14
View File
@@ -4,3 +4,17 @@
ansible.builtin.package: ansible.builtin.package:
name: "{{ ufw_package_name }}" name: "{{ ufw_package_name }}"
state: present 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 }}"
+1
View File
@@ -23,3 +23,4 @@
when: when:
- ufw_enabled - ufw_enabled
- ufw_manage_rules - ufw_manage_rules
- __ufw_can_configure | default(true)
+25 -8
View File
@@ -5,8 +5,10 @@
python3 -I scripts/check_scenarios_load_checkout.py < scenario-dirs 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 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 own env can change it. Also checks that molecule's prerun, its install of the collection, is off
a scenario would load another copy, or none. 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 import json
@@ -16,6 +18,8 @@ import sys
import tempfile import tempfile
from molecule.config import Config 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__))) CHECKOUT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
RULE = ( RULE = (
@@ -23,20 +27,25 @@ RULE = (
" copy: the scenario selector ignores galaxy.yml on that rule" " copy: the scenario selector ignores galaxy.yml on that rule"
" (.gitea/workflows/AGENTS.md, Molecule)" " (.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): def scenario_config(scenario):
"""The environment molecule gives ansible-playbook in `scenario`, as a role scenario runs it.""" """Molecule's config of `scenario` as `molecule converge` builds it there, and its base config."""
parts = scenario.split("/") parts = scenario.split("/")
cwd = os.path.join(CHECKOUT, *parts[:2]) if parts[0] == "roles" else CHECKOUT 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) os.chdir(cwd)
base = lookup_config_file(LOCAL_CONFIG_SEARCH)
config = Config( config = Config(
os.path.relpath(os.path.join(CHECKOUT, scenario, "molecule.yml")), os.path.relpath(os.path.join(CHECKOUT, scenario, "molecule.yml")),
args={}, args={"base_config": [base] if base else []},
command_args={"subcommand": "converge"}, command_args={"subcommand": "converge"},
) )
return dict(config.provisioner.env) return config, base
def collection_paths(env, cwd): def collection_paths(env, cwd):
@@ -79,8 +88,16 @@ def main():
os.environ.setdefault("ANSIBLE_HOME", home) os.environ.setdefault("ANSIBLE_HOME", home)
for scenario in filter(None, sys.stdin.read().splitlines()): for scenario in filter(None, sys.stdin.read().splitlines()):
scenario_dir = os.path.join(CHECKOUT, scenario) 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 = [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) found = loaded_copy(paths)
if found and os.path.realpath(found) == CHECKOUT: if found and os.path.realpath(found) == CHECKOUT:
continue continue
+1 -1
View File
@@ -30,7 +30,7 @@ fi
ansible --version ansible --version
molecule --version molecule --version
# The collection under test first; molecule does not install it again (prerun is off in # 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" 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 # 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_<fact>` fails its scenario here instead of in a consumer's inventory. # role that reads a bare `ansible_<fact>` fails its scenario here instead of in a consumer's inventory.
@@ -43,6 +43,11 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase):
self.ac_root = self.tmp / "ac" self.ac_root = self.tmp / "ac"
self.checkout = collection(self.ac_root) self.checkout = collection(self.ac_root)
(self.checkout / "scripts").mkdir() (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") shutil.copy(SCRIPT, self.checkout / "scripts")
self.other = self.tmp / "other" self.other = self.tmp / "other"
collection(self.other) collection(self.other)
@@ -55,10 +60,14 @@ class CheckScenariosLoadCheckoutTest(unittest.TestCase):
"ANSIBLE_COLLECTIONS_PATH": f"{self.ac_root}:{self.other}", "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 = self.checkout / path
d.mkdir(parents=True, exist_ok=True) d.mkdir(parents=True, exist_ok=True)
config = {"driver": {"name": "default"}, "platforms": [{"name": "instance"}]} config = {
"driver": {"name": "default"},
"platforms": [{"name": "instance"}],
**keys,
}
if env: if env:
config["provisioner"] = {"name": "ansible", "env": env} config["provisioner"] = {"name": "ansible", "env": env}
(d / "molecule.yml").write_text(yaml.safe_dump(config)) (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("must load mortis.kamino from the checkout", result.stdout)
self.assertIn(found, 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): def test_the_checkout_first_passes(self):
# the scenarios inherit prerun off from the base config
result = self.run_check( result = self.run_check(
"roles/alpha/molecule/default\nextensions/molecule/image-smoke\n" "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.assert_refused(result, "extensions/molecule/image-smoke")
self.assertNotIn("roles/alpha/molecule/default", result.stdout) 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__": if __name__ == "__main__":
unittest.main() unittest.main()