Skip to main content Link Menu Expand (external link) Document Search Copy Copied

IPtables with Ansible

Set ip_forward=1 in systctl

- ansible.posix.sysctl:
    name: net.ipv4.ip_forward
    value: '1'
    sysctl_set: true
    state: present
    reload: true

The out_interface is usually the public interface!

- name: Get default route
  shell: ip route | grep default | awk '{print $5}'
  register: public_interface

- name: Print public interface
  debug:
    msg: "Public interface is "

- name: Create Iptables NAT chain
  iptables:
    table: nat
    chain: POSTROUTING
    out_interface: ''
    source: ''
    destination: ''
    jump: MASQUERADE
    protocol: ''
    comment: Ansible NAT Masquerade
  vars:
    masquerade_source: '10.10.1.0/24'                                                                                                                                                                              masquerade_destination: '0.0.0.0/0'
    masquerade_jump: MASQUERADE
    masquerade_protocol: 'all'

iptables-persistent to store current rules to file

- name: Save current state of the firewall in system file
  community.general.iptables_state:
    ip_version: ipv4
    state: saved
    path: /etc/iptables/rules.v4

Optional steps

- name: Set ip forwarding on in /proc and in the sysctl file and reload if necessary
  ansible.posix.sysctl:
    name: net.ipv4.ip_forward
    value: '1'
    sysctl_set: true
    state: present
    reload: true

- name: Allow related and established connections
  ansible.builtin.iptables:
    chain: INPUT
    ctstate: ESTABLISHED,RELATED
    jump: ACCEPT

- name: Allow new incoming SYN packets on TCP port 22 (SSH)
  ansible.builtin.iptables:
    chain: INPUT
    protocol: tcp
    destination_port: 22
    ctstate: NEW
    syn: match
    jump: ACCEPT
    comment: Accept new SSH connections.