requires_ansible and every role's min_ansible_version said 2.19, which CI never tested; CI tests only the pinned ansible-core (2.22). The floor now equals that minor. ansible-lint 26.10.1's built-in supported list ends at 2.19, so .ansible-lint adds 2.22 for meta-runtime[unsupported-version]. BREAKING CHANGE: ansible-core 2.19, 2.20 and 2.21 (and controller Python 3.12) are no longer supported. Closes #164 Assisted-by: Claude Code
ufw
Installs UFW and applies sysctl overrides, /etc/ufw/before.rules, default policies and allow rules, then enables it, refusing to run when the rules would lock the host out of SSH. The main entry point applies ufw_rules only; a service role passes its own rules explicitly through the service_rules entry point, and orphan_rules cleans up the rules of services that are no longer managed. Variables and their types are defined in meta/argument_specs.yml, which is the source of truth.
Supported platforms
Ubuntu 24.04 (noble), the image the molecule scenario runs on. 22.04 (jammy) is listed in meta/main.yml but not verified by a test. The role uses ansible.builtin.package and the community.general.ufw module; community.general is a dependency of the Collection.
Requirements and run order
- Use it by its fully qualified name,
mortis.kamino.ufw. - Run the
system_baselinerole of this Collection before this role. UFW's stock/etc/ufw/sysctl.confre-applies sysctl values when UFW is enabled, which undoes baseline hardening. Mirror the baseline values inufw_sysctl_overrides. - Main entry point: apply it in the play that hardens a host, after
system_baselineandsystemd_hardening, beforefail2ban. service_rulesentry point: called by each service role that owns firewall rules (include_rolewithtasks_from: service_rules), after the main entry point has run, passingufw_service_nameandufw_service_rules.orphan_rulesentry point: called once per host after every service role ran, withufw_managed_ownersset to the owners that are still managed.ufw_rulesmust contain an allow or limit rule for the SSH port (see Notes).
Role variables
Main entry point:
| Variable | Default | Required | Description |
|---|---|---|---|
ufw_enabled |
true |
no | Skip all UFW configuration when false (the package is still installed). |
ufw_manage_rules |
true |
no | Skip the ufw_rules schema check, the lock-out guard and rule application when false. Before-rules validation and before.rules, defaults and enable still run (gated on ufw_enabled). |
ufw_defaults |
incoming: deny, outgoing: allow, routed: deny |
no | Default policies. All three keys are read, so override all of them. |
ufw_logging |
"on" |
no | UFW logging level. |
ufw_require_ssh_allow |
true |
no | Enable the SSH lock-out guard. |
ufw_ssh_port |
ansible_port or 22 |
no | TCP port the guard looks for. |
ufw_rules |
[] |
no | Base rule list: rule (allow, deny, reject, limit), port, proto, from, to, interface, direction, comment, delete (see Notes). |
ufw_before_rules |
[] |
no | Entries added as ACCEPT lines to before.rules: interface, proto, port, from, comment. |
ufw_sysctl_overrides |
[] |
no | {name, value} pairs written to /etc/ufw/sysctl.conf. |
There is no discovery by variable name, and a variable that looks like one fails the play: at the start of the role, a guard refuses any variable whose name matches ^.+_ufw_(before_)?rules$ (a foo_ufw_rules or foo_ufw_before_rules defined as any variable visible to the host: inventory, play and role vars, extra vars, set_fact and registered variables) and names it in the error. Pass service rules through tasks_from: service_rules (ufw_service_name, ufw_service_rules; a caller's own <role>_ufw_service_rules does not match), or put base rules in ufw_rules. The guard is unconditional, has no switch, and carries the tags ufw and always. ufw_before_rules is base-only: no entry point adds before-rules.
Tags
ufw (everything), ufw_install, ufw_sysctl, ufw_aggregate, ufw_validate, ufw_before_rules, ufw_defaults, ufw_rules, ufw_enable.
Skipping ufw_aggregate leaves the lists the later tasks read (ufw_aggregated_rules, ufw_aggregated_before_rules) undefined or stale, so do not select a later tag alone.
Example play
- name: Harden and firewall the servers
hosts: servers
roles:
- role: mortis.kamino.ufw
vars:
ufw_rules:
- {rule: allow, port: 22, proto: tcp, comment: ssh}
- {rule: allow, port: 8080, proto: tcp, from: 10.0.0.0/8, comment: web}
service_rules entry point
A service role that owns firewall rules calls the role with include_role and tasks_from: service_rules after the main entry has run, with apply: {tags: [...]} so --tags <role> reaches these tasks. The entry point installs nothing and touches no default policy, no before.rules and no base rule. Outside check mode (--check or the check_mode keyword; the role detects it with a skipped probe task, not ansible_check_mode) it fails when ufw is not installed and active. In check mode it skips the reconcile only when ufw status fails (ufw not installed yet, the main entry may not have reached the host); a host with ufw installed but inactive is reconciled as usual.
| Variable | Default | Required | Description |
|---|---|---|---|
ufw_service_name |
none | yes | Owner of the rules, ^[a-z0-9_]+$. base is reserved. |
ufw_service_rules |
none | yes for present |
List of rule mappings with the keys ufw_rules accepts except delete (other keys are refused; interface needs direction). An empty list makes every rule of the owner stale, and is refused together with ufw_purge_stale: true. |
ufw_service_state |
present |
no | present or absent. |
ufw_purge_stale |
false |
no | For present only. false: report stale rules. true: delete them. absent always deletes. |
Tags: ufw, ufw_service_rules. They select the entry point's tasks under --tags; the tags of an include_role caller do not reach the included tasks unless the caller sets apply: {tags: [...]} on its include_role. Skipped with a debug message when ufw_enabled or ufw_manage_rules is false.
- name: Open the service ports
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: service_rules
apply:
tags: [webapp]
vars:
ufw_service_name: webapp
ufw_purge_stale: true
ufw_service_rules:
- {rule: allow, port: 3000, proto: tcp, comment: web}
Tag format. Each rule is applied with the comment ansible-ufw[<owner>:<key>]: <text>. <key> is the first ten hex characters of the sha1 of rule|port|proto|from|to|interface|direction (null counts as omitted; any, Anywhere, 0.0.0.0/0 and ::/0 in from/to count as empty, a host mask /32 on IPv4 or /128 on IPv6 is dropped, incoming counts as in), so changing any of those fields is a new rule and the old one becomes stale; changing only the comment updates the rule in place (verified on ufw 0.36). <text> is the rule's own comment. Comments must be printable ASCII without a single quote or backslash and without leading or trailing whitespace. The prefix and the regexes that read it back are role defaults (ufw_tag_prefix, ufw_tag_regex, ufw_tag_comment_regex); changing the prefix orphans rules already tagged.
Stale rules. The role reads ufw show added and looks only at lines whose comment carries a tag of this owner; no rule syntax is parsed. A stale rule is one whose key is not in the desired list. With ufw_service_state: absent the desired list is empty, so every rule of the owner is stale.
Purge. With ufw_purge_stale: false (the default) stale rules of a present owner are only reported. With true, or with ufw_service_state: absent (an explicit removal request that does not need ufw_purge_stale), they are deleted once every desired rule was applied, by ufw --force delete <printed line> (never by rule number, so the comment matches and the IPv4 and IPv6 rules go together). Check mode never deletes. Afterwards the role re-reads the rules and fails unless every desired rule is present, no stale rule remains and the SSH rule is unchanged.
Never deleted. Rules without a tag (base rules, the SSH rule, manual rules) and rules of other owners. A stale line is deleted only when it is an explicit single numeric port other than ufw_ssh_port (ufw allow 7401/tcp, a deny works too). Every other line may open SSH and is kept and listed as a possible SSH path: no port (allow in on tailscale0, allow from 10.0.0.0/24), a port range or list (20:30/tcp, 22,80/tcp), the word ssh or openssh outside the comment (a service name or an application profile, any case), the SSH port itself, or a line the SSH-port regex matches. ufw_port_token_regex finds the port tokens.
Refused before anything changes. A rule listed twice by one owner; a rule whose spec another owner already holds (ufw stores identical specs once, so the tag would swap on every run); a rule that allows or limits ufw_ssh_port over TCP in the incoming direction (it would retag the untagged base SSH rule, and a purge could then delete it). Stale lines that hold characters outside printable ASCII, or braces, are refused rather than turned into a command. A desired rule that matches an untagged manual rule exactly adopts it: its comment is replaced by the tag and the owner manages it from then on.
Limitations. Two owners cannot hold the same spec: a shared rule such as 80/443 aborts the second owner. A service rule with the same spec as a rule of the base ufw_rules list is retagged by the service call and rewritten by the next base run, back and forth, so keep the two lists disjoint.
orphan_rules entry point
service_rules cleans up the rules of an owner only while that owner's role still runs. A service removed from a host leaves its tagged rules behind, and nothing calls service_rules for it again. include_role with tasks_from: orphan_rules finds those rules.
An orphan is a rule tagged ansible-ufw[<owner>:<key>] whose owner is neither in ufw_managed_owners nor in ufw_reserved_owners.
| Variable | Default | Required | Description |
|---|---|---|---|
ufw_managed_owners |
none | no (undefined or empty: does nothing, see below) | Owners that are still managed, each ^[a-z0-9_]+$. When a play derives it from a per-host list of service roles, each owner name must equal the role name in that list, because that is the ufw_service_name the role passes. |
ufw_purge_orphans |
false |
no | false: orphans are reported. true: they are deleted. |
- Fail closed.
ufw_managed_ownershas no default. While it is undefined or empty the entry point does nothing at all, not even a report, because an unknown list would make every owner an orphan. A malformed entry fails the play. - Report only by default. The role default is
false; a caller that wants the purge passestruein the taskvars:of its call, rather than in inventory variables that every play would see. The log lists three groups: orphans that can be deleted (said to be deleted only when they were), orphans kept as a possible SSH path, and orphans kept as unparseable or unsafe (characters outside printable ASCII, or braces; only owner and key are shown). Deletion needsufw_purge_orphans: true(a boolean, anything else fails), and never happens in check mode. - Never touched. Untagged rules (base, SSH, manual) and rules of managed or reserved owners (
base). A tagged line is deleted only when it is an explicit single numeric port other thanufw_ssh_port(ufw allow 7401/tcp, a deny works too). Every other line may open SSH and is kept and listed as a possible SSH path: no port (allow in on tailscale0,allow from 10.0.0.0/24), a port range or list (20:30/tcp,22,80/tcp), the wordsshoropensshoutside the comment (a service name or an application profile, any case), the SSH port itself, or a line the SSH-port regex matches.ufw_port_token_regexfinds the port tokens. The same rule guards the stale purge ofservice_rules. - Verified. After a delete the rules are read again; the play fails unless exactly the deleted lines are gone and every other rule, the SSH rule included, is unchanged.
- Skipped with a debug message when
ufw_enabledorufw_manage_rulesis false, and with a debug message when ufw is not installed or not active (the play does not fail). - Limitation. The owner of a rule is the
ufw_service_namea role passes. A role that is called by another role, which callsservice_ruleswith its own owner name, is reported as an orphan unless that name is inufw_managed_owners. Keep each role'sufw_service_nameequal to its own role name. - Tags:
ufw,ufw_orphan_rules. As forservice_rules, aninclude_rolecaller needsapply: {tags: [...]}for its own tags to reach the tasks. - The parse, the SSH regex, the line check, the delete and the verify step duplicate
tasks/service_rules.yml: keep them in step.
- name: Purge the rules of owners that are no longer managed
ansible.builtin.include_role:
name: mortis.kamino.ufw
tasks_from: orphan_rules
apply:
tags: [ufw, ufw_orphan_rules]
vars:
ufw_managed_owners: "{{ host_services | default([]) }}"
ufw_purge_orphans: true
tags: [ufw, ufw_orphan_rules]
Notes
- Lock-out guard:
defaults.ymlsets the deny policy beforerules.ymladds any rule. Whenufw_enabled,ufw_manage_rulesandufw_require_ssh_alloware true and the incoming default is deny or reject, the play fails unlessufw_rulesholds an allow or limit rule forufw_ssh_portthat is TCP (or has noproto) and hasdirection: inor nodirection.direction: incoming, which the module accepts, is not counted, so writein. Anyfrom,toorinterfacerestriction still counts; the guard cannot know the control host's address. An entry withdelete: truenever counts. - Replacing a base rule: list the new rule and the old one with
delete: true(a boolean). Deletes are applied after every other rule, whatever their place in the list, so the replacement exists before the old rule goes, which matters when narrowing the SSH rule. The comment of a delete entry is not sent, so the rule matches whatever its comment, and a delete of a rule that is already gone changes nothing. An entry that deletes a rule the same list adds (samerule,port,proto,from,to,interfaceanddirection, where nodirectionisinand nofromortoisany) fails the play. A delete without an address removes the IPv4 and the IPv6 rule; a replacement with an IPv4fromallows IPv4 only, so check that the hosts you connect from are covered before narrowing SSH.deleteis forufw_rulesonly;service_rulesremoves its own stale rules. before.rulesis a template derived from UFW's ownbefore.rules(GPL-3.0-only, seeNOTICE) that fully replaces the stock file, including a loopback accept, conntrack (established accept and INVALID-state drop), ICMP and mDNS/UPnP entries. It is deployed wheneverufw_enabledis true, even with no before-rules.- Rule schema is asserted before anything changes:
rulemust be allow, deny, reject or limit,porta positive integer,prototcp or udp, and each rule needsport,from,toorinterface. - UFW is only re-enabled when
ufw status verboseshows it inactive or the logging line differs, because the module rewrites rules and re-applies sysctl on every call. - The
Reload UFWhandler runsufw reload. no_logis not used: the role handles no secrets.