ansibleufw

How to configure UFW reject policy in ansible without being disconnected?


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.


Solution

  • 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