ansibleufw

How to run an ansible task if ufw is enabled?


I need to run some tasks only if ufw is enabled on the Ubuntu server.

Pseudocode looks like:

 - name: detect if ufw is enabled
   magical_module: ???
   register: ufw_is_enabled

 - name: my task
   when: ufw_is_enabled

I see only this nonelegant solution:

root@test:~# ufw status
Status: inactive

Maybe there is some file when ufw is enabled? In this case, it will be possible to use stat module. Any other solutions?


Solution

  • Something along the lines of:

        - name: check whether ufw status is active
          shell: ufw status
          changed_when: false
          register: ufw_check
    
        - debug:
            msg: "{{ ufw_check }}"
    
        - name: do something if ufw is enabled
          shell: echo
          when: "'inactive' not in ufw_check.stdout"
    

    Make sure to use become: true, since root privileges are required to successfully execute the command.

    To manage systems with the UFW module, see this Ansible module

    What you can do, for example is, disable UFW on systems on which you want it disabled:

        - name: Disable UFW on hosts
          ufw:
            state: disabled # unloads firewall and disables firewall on boot.