--- - name: Configure IPv4 firewall via iptables hosts: finlog_dev become: true gather_facts: false vars: firewall_tcp_ports: [ 22, 80, 443 ] # extend as needed firewall_udp_ports: [ ] # e.g. [53] tasks: - name: Generate IPv4 firewall rules ansible.builtin.copy: dest: /etc/iptables/rules.v4 content: | *filter :INPUT DROP [0:0] :FORWARD DROP [0:0] :OUTPUT ACCEPT [0:0] # Always allow loopback -A INPUT -i lo -j ACCEPT # Accept already established/related -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT # Drop invalid early -A INPUT -m conntrack --ctstate INVALID -j DROP # Allow TCP ports {% for p in firewall_tcp_ports | default([]) -%} -A INPUT -p tcp --dport {{ p }} -j ACCEPT {% endfor -%} # Allow UDP ports {% for p in firewall_udp_ports | default([]) -%} -A INPUT -p udp --dport {{ p }} -j ACCEPT {% endfor -%} COMMIT owner: root group: root mode: '0644' when: not ansible_check_mode - name: Restore rules now ansible.builtin.shell: iptables-restore < /etc/iptables/rules.v4 args: executable: /bin/bash changed_when: false when: not ansible_check_mode - name: Save rules for persistence ansible.builtin.command: netfilter-persistent save changed_when: false when: not ansible_check_mode - name: Show filter table (iptables -S) ansible.builtin.command: iptables -S changed_when: false when: not ansible_check_mode