I have a blockinfile task that sets some lines in /etc/ufw/before.rules, and which notifies handler to reload ufw if the task registers a change. I was running it on a host and noticed that I had the same prerouting rule from before.rules multiple times, so I took a closer look at the task as I was running it, and I noticed that it keeps triggering every time it runs.
- name: set nat and port forwarding start section
blockinfile:
dest: /etc/ufw/before.rules
marker: "# {mark} bbg nat rules"
insertbefore: "# Don't delete these required lines, otherwise there will be errors"
block: |
# NAT table rules
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
when: firewall.nat is defined or firewall.pf is defined notify:
- reload ufw
- name: set individual port forwarding rules if specified
blockinfile:
dest: /etc/ufw/before.rules
insertafter: "# END bbg nat rules"
marker: "# {mark} {{ item.desc|default(omit) }}"
block: |
# Forward port for {{ item.desc }}
-A PREROUTING -p tcp --dport {{ item.src_port }} -j REDIRECT --to-port {{ item.dst_port }}
notify:
- reload ufw
- name: set individual nat rules if specified
blockinfile:
dest: /etc/ufw/before.rules
insertbefore: "# BEGIN bbg nat rules commit"
marker: "# {mark} {{ item.desc|default(omit) }}"
block: |
# Forward traffic through {{ item.out_in|default(eth0) }} - Change to match you out-interface for {{ item.desc|default(omit) }}
-A POSTROUTING -s {{ item.source|default("0.0.0.0/0") }} -d {{ item.dest|default("0.0.0.0/0") }} -o {{ item.out_in|default(eth0) }} -j MASQUERADE with_items: "{{ firewall.nat|default(omit) }}"
when: firewall.nat is defined
notify:
- reload ufw
- name: set nat rules commit if specified
blockinfile:
dest: /etc/ufw/before.rules
marker: "# {mark} bbg nat rules commit"
insertbefore: "# Don't delete these required lines, otherwise there will be errors"
block: |
# don't delete the 'COMMIT' line or these nat table rules won't
# be processed
COMMIT
when: firewall.nat is defined or firewall.pf is defined notify:
- reload ufw