16

I'm trying to configure UFW in Ansible like this:

- name: Set firewall default policy
  ufw: state=enabled policy=reject
  sudo: true

- name: Allow SSH in UFW
  ufw: rule=allow port=22 proto=tcp

The problem is that as soon as the "Set firewall default policy" is executed ansible drops the connection to the server:

TASK: [Set firewall default policy] *******************************************
changed: [xxx]

TASK: [Allow SSH in UFW] ******************************************************
fatal: [xxx] => {'msg': 'FAILED: [Errno 61] Connection refused', 'failed': True}

FATAL: all hosts have already failed -- aborting

To me it looks like the SSH session is terminated when the reject policy has been applied. How do I solve this? I'm logging in with username/password authentication (i.e. no SSH key) if that makes any difference.

Johan
  • 37,479
  • 32
  • 149
  • 237

2 Answers2

18

The order you add rules to the UFW is not important. So you can just reverse order of rules. The trick is to add rule to allow your current connection before adding the default rule, which will deny it (and therefore instantly disconnect).

- name: Allow SSH in UFW
  ufw: rule=allow port=22 proto=tcp

- name: Set firewall default policy
  ufw: state=enabled policy=reject
  become: true
Yaroslav Admin
  • 13,880
  • 6
  • 63
  • 83
  • I'm confused. You say "the order is not important" but then your solution is to change the order? Which is it? – Sentry Oct 10 '20 at 11:25
  • 1
    The order is not important in a sense that you will end up with the same policy independently of the rules order. But it is important in a sense that if you add a rule, which blocks your current connection, you can’t add a rule, which allows your current connection anymore ‍♂️ – Yaroslav Admin Oct 10 '20 at 11:30
  • I've tried setting the default policy towards the beginning, and towards the end (after allowing ssh port). It has worked and failed in both arrangements. – Bix Aug 11 '21 at 23:13
2

Here is the solution that worked for me, from ansible github

- name: Configure the kernel to keep connections alive when enabling the firewall
  sysctl:
    name: net.netfilter.nf_conntrack_tcp_be_liberal
    value: 1
    state: present
    sysctl_set: yes
    reload: yes

- name: Enable ufw
  ufw: state=enabled

You will need to install ansible.posix on the host machine with

ansible-galaxy collection install ansible.posix
Bix
  • 760
  • 8
  • 22