fix(ufw, fail2ban): pass --check on a host without the package

Under --check the package task only reports a change, so on a fresh host
the tasks after it ran against a missing binary, /etc directory or unit
and failed. They now skip when the install would change in check mode.

fail2ban registers __fail2ban_install and guards its template, service,
config test, jail tasks and handler with the standard
`not ansible_check_mode or ... is not changed` guard. ufw registers
__ufw_install plus a command probe (ansible_check_mode is not set for a
play-level check_mode inside include_role), combined once in vars/main.yml
as __ufw_can_configure. flush_handlers is left unguarded: the handler it
runs is guarded itself.

A check-absent scenario per role purges the package, refreshes the APT
cache and runs only `check`, so each fix is tested; one scenario covering
both would make the ufw role a user of fail2ban and select the ufw and
traefik scenarios on every fail2ban change.

Fixes #478

Assisted-by: Claude Code
This commit is contained in:
Defame1297 committed 2026-11-29 16:39:45 +00:00
1 parent 0173f6f226
commit 924a0ea7a7
20 files changed
+234 -9

No files matched your search

+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.
- 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 <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.
- `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.
+2
View File
@@ -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
@@ -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
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
+1
View File
@@ -7,3 +7,4 @@
# Required for `backend = systemd` jails (journalmatch), e.g. gitea's.
- python3-systemd
state: present
register: __fail2ban_install
+6 -1
View File
@@ -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'
+4
View File
@@ -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,6 +46,7 @@
group: root
mode: "0644"
notify: Reload Fail2Ban
when: not ansible_check_mode or __fail2ban_install | default({}) is not changed
# 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.
@@ -54,4 +57,5 @@
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]
+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 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 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.
@@ -0,0 +1,12 @@
---
# 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}
@@ -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
mode: "0644"
notify: Reload UFW
when: ufw_enabled
when:
- ufw_enabled
- __ufw_can_configure
# 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
+9 -3
View File
@@ -4,18 +4,24 @@
community.general.ufw:
direction: incoming
policy: "{{ ufw_defaults.incoming }}"
when: ufw_enabled
when:
- ufw_enabled
- __ufw_can_configure
- 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
- 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
+4 -1
View File
@@ -11,7 +11,9 @@
environment:
LC_ALL: C
LANGUAGE: C
when: ufw_enabled
when:
- ufw_enabled
- __ufw_can_configure
- name: Enable UFW
become: true
@@ -26,6 +28,7 @@
else 'Logging: on (' ~ ufw_logging ~ ')' }}
when:
- ufw_enabled
- __ufw_can_configure
- >-
'Status: active' not in ufw_status_verbose.stdout
or ufw_logging_expected not in ufw_status_verbose.stdout
+8
View File
@@ -4,3 +4,11 @@
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
+1
View File
@@ -23,3 +23,4 @@
when:
- ufw_enabled
- ufw_manage_rules
- __ufw_can_configure
+3
View File
@@ -1,2 +1,5 @@
---
ufw_package_name: ufw
# False only when a check-mode run would install ufw: the binary and /etc/ufw are then missing, so
# the tasks that need them are skipped. True when install.yml did not run (its tags were skipped).
__ufw_can_configure: "{{ __ufw_install | default({}) is not changed or __ufw_install_probe is not skipped }}"