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
fail2ban
Installs Fail2Ban, writes /etc/fail2ban/jail.local from fail2ban_jails, ensures the service runs and verifies the enabled jails loaded. A second entry point, service_jail, lets a service role deploy its own jail and filter into jail.d. Variables and their types are defined in meta/argument_specs.yml, which is the source of truth.
Supported platforms
Ubuntu 24.04 (noble) and 26.04 (resolute), the platforms the molecule scenario runs on. The default sshd jail reads the systemd journal because sshd logs there on those releases. The role installs python3-systemd, which backend = systemd jails need.
Ubuntu hosts only: the role targets the Ubuntu guests whose system_baseline profiles install fail2ban; Proxmox hosts are not targeted.
Requirements and run order
- Use it by its fully qualified name,
mortis.kamino.fail2ban. - No hard prerequisite.
system_baselinealso listsfail2banamong its packages, so it normally runs first; this role installs it regardless. - Main entry point: apply it after
ufwin the play that hardens a host. service_jailentry point: called by a service role such asgitea(include_rolewithtasks_from: service_jail) after it has installed the service.- A file named by a jail's
logpathmust exist whenfail2ban-client -truns, or the configuration test fails. - Role dependencies: none.
Role variables
Main entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
fail2ban_package_name |
fail2ban |
no | Package name. |
fail2ban_jails |
one sshd jail (systemd backend, maxretry 3, bantime 1h, findtime 10m) |
no | Jails written to jail.local. Each needs name, enabled, filter, maxretry, bantime, findtime and logpath, journalmatch or backend: systemd. |
fail2ban_ignoreip |
127.0.0.1/8, ::1 |
no | Addresses, networks or hostnames never banned, on every jail (written as ignoreip in [DEFAULT], so service jails in jail.d are covered). Add the machine that runs Ansible or a CI runner. An empty list exempts nothing, loopback included; entries hold no whitespace. |
fail2ban_service |
enabled: true, state: started |
no | Service enablement and state. |
fail2ban_defaults |
maxretry: 5, bantime: 600, findtime: 600 |
no | Fallbacks for those keys. Only used by the service_jail entry point; main-entry jails must set all three (tasks/validate.yml asserts them), so there the fallback only applies when validation is skipped, for example under --tags fail2ban_configure. |
service_jail entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
fail2ban_service_name |
none | yes | Jail name and file name under filter.d and jail.d. |
fail2ban_service_jail |
none | yes | Jail mapping; needs logpath or journalmatch. |
fail2ban_service_filter |
none | yes | Filter mapping; needs failregex, optional ignoreregex. |
fail2ban_package_name, fail2ban_defaults |
as above | no | Read from the role defaults. |
Entry points
main: writesjail.localfromfail2ban_jailsand runs the service, as in the first play of the example.service_jail: a service role's own jail and filter, seeservice_jail.
service_jail
It deploys the service's jail and filter into jail.d. Its inputs are in the second table under Role variables, and the second play of the example calls it.
- Each service owns
jail.d/<name>.local, so one play cannot overwrite another service's jail.jail.localonly holdsfail2ban_jails. fail2ban_service_jailandfail2ban_service_filtermust be passed as a single templated expression so they stay mappings, not strings or lists.
Tags
Main entry point: fail2ban (everything), fail2ban_install, fail2ban_validate, fail2ban_configure, fail2ban_service.
service_jail: fail2ban, fail2ban_install, fail2ban_service_jail.
Example play
- hosts: containers
roles:
- role: mortis.kamino.fail2ban
vars:
fail2ban_defaults:
maxretry: 5
bantime: 600
findtime: 600
- hosts: gitea
tasks:
- name: Deploy a service jail
ansible.builtin.include_role:
name: mortis.kamino.fail2ban
tasks_from: service_jail
vars:
fail2ban_service_name: gitea
fail2ban_service_jail: "{{ gitea_fail2ban_jail }}"
fail2ban_service_filter: "{{ gitea_fail2ban_filter }}"
Tests
The scenario molecule/default/ runs in CI only, on two platforms: ${MOLECULE_IMAGE} (Ubuntu 24.04) and ${MOLECULE_IMAGE_2604} (Ubuntu 26.04). It runs check before the converge (a fresh host, where the image already has fail2ban installed) and after it (a configured host).
- Converge applies the main entry point with an extra
fail2ban_ignoreipnetwork and callsservice_jailtwice, one jail with alogpathand one with ajournalmatch. - Converge also runs inputs that must be refused: a service filter without
failregex, and afail2ban_ignoreipentry with whitespace, a plain string instead of a list, and an entry starting with;. Thefail2ban_ignoreiprefusals are matched on their message. - Verify checks that the
sshdjail does not read/var/log/auth.log, thatjail.localholds the configuredignoreipin[DEFAULT]and none of the refused values, that each service jail has its ownjail.dfile and the refused one left no file, thatfail2ban-client -tpasses, and that the running daemon loadedsshd,svc-aandsvc-band applies theignoreipnetwork to both a base jail and a service jail. - The side effect bans an address and rewrites
jail.localwith a newmaxretry; 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:
--checkis the supported preview; a play-levelcheck_mode: trueis 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-clientand the unit. fail2ban_ignoreiplives in the[DEFAULT]section ofjail.local, so it also applies to the jails thatservice_jailwrites tojail.d. The exemption only exists once the main entry point has writtenjail.localon that host:service_jaildoes not readfail2ban_ignoreip, so a host that uses onlyservice_jailhas none.fail2ban_ignoreipreplaces anignoreipset injail.conforjail.d/*.conf, which Fail2Ban reads beforejail.local; ajail.d/*.localfile 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 offail2ban_ignoreipruns under thefail2ban_validatetag, so--tags fail2ban_configureskips it. - Changing
jail.localor 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 towardmaxretry; a reload applies the new settings to the running jails. When the whole role runs, the reload comes afterfail2ban-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_ignoreipnow covers (only a restart skips ignored addresses when it restores bans, so runfail2ban-client unban <address>to release one at once, or wait for the ban to expire); it does not change bans that already exist whenbantimechanges; and it does not apply server-level settings (loglevel,dbfile,socket,pidfile), which this role does not write. A changedbackendrestarts that jail by itself. - With
--tags fail2ban_configureonly,fail2ban-client -tdoes not run before the reload; the reload (fail2ban-client reloadin the upstream unit) still rejects a bad configuration and leaves the running daemon alone. fail2ban-client -truns 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_logis not used: the role handles no secrets.