Ansible: disable service only if present

2019-07-15 02:03发布

问题:

Is there any nice way to do disable and stop a service, but only if it's installed on server? Something like this:

- service: name={{ item }} enabled=no state=stopped only_if_present=yes
  with_items:
  - avahi-daemon
  - abrtd
  - abrt-ccpp

Note that "only_if_present" is a keyword that doesn't exist right now in Ansible, but I suppose my goal is obvious.

回答1:

I don't know what is the package name in your case, but you can do something similar to this:

- shell: dpkg-query -W 'avahi'
  ignore_errors: True
  register: is_avahi
  when: ansible_distribution == 'Debian' or ansible_distribution == 'Ubuntu'

- shell: rpm -q 'avahi'
  ignore_errors: True
  register: is__avahi
  when: ansible_distribution == 'CentOS' or ansible_distribution == 'Red Hat Enterprise Linux'

- service: name=avahi-daemon enabled=no state=stopped
  when: is_avahi|failed

Update: I have added conditions so that the playbook works when you have multiple different distros, you might need to adapt it to fit your requirements.



标签: ansible