如果启用了 ufw,如何 运行 一个可靠的任务?

How to run an ansible task if ufw is enabled?

只有在 Ubuntu 服务器上启用了 ufw 时,我才需要 运行 一些任务。

伪代码如下:

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

 - name: my task
   when: ufw_is_enabled

我只看到这个不优雅的解决方案:

root@test:~# ufw status
Status: inactive

启用ufw时可能有一些文件?在这种情况下,可以使用 stat 模块。还有其他解决方案吗?

大致如下:

    - name: check whether ufw status is active
      shell: ufw status
      changed_when: False
      ignore_errors: True
      register: ufw_check

    - debug:
        msg: "{{ ufw_check }}"

    - name: do something if ufw is enabled
      shell: echo
      when: "'inactive' not in ufw_check.stdout"

确保使用 become: True,因为这是必需的。

要使用 UFW 模块管理系统,see this Ansible module

例如,您可以在要禁用它的系统上禁用 UFW:

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