仅在安装了软件包的情况下,禁用系统服务

问题描述:

这就是我所拥有的

- name: disable os firewall - firewalld
  systemd:
    name: firewalld
    state: stopped
    enabled: no

此任务在安装了firewalld软件包的主机上工作正常,但在未安装firewalld软件包的主机上失败.

This task works fine on hosts where firewalld package is installed but fails on hosts where it is not.

什么是最好的简单方法,以确保它可以处理未安装firewalld的主机?我不想使用任何CMDB,因为这是附加设置.另外,我希望任务是幂等;使用dpkgrpm之类的shell命令来查询是否安装了firewalld会使我不想看到的Ansible Playbook摘要报告更改.

What is the best simple approach to make sure it can handle hosts which do not have firewalld installed? I do not want to use any CMDB as it's an additional setup. Also, I want the task to be idempotent; using a shell command like dpkg or rpm to query if firewalld is installed makes the ansible playbook summary report changes which I do not want.

以下是使用failed_when:的示例.尽管它确实每次运行,但是如果未安装该软件包,它将忽略失败:

Here is an example using failed_when:. While it does run every time, it ignores the failure if the package is not installed:

- name: Stop and disable chrony service
  service:
    name:    chronyd
    enabled: no
    state:   stopped
  register: chronyd_service_result
  failed_when: "chronyd_service_result is failed and 'Could not find the requested service' not in chronyd_service_result.msg"