Petr
Petr

Reputation: 14485

Ansible: disable service only if present

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.

Upvotes: 5

Views: 10586

Answers (2)

Universal solution for systemd services:

- name: Disable services if enabled
  shell: if systemctl is-enabled --quiet {{ item }}; then systemctl disable {{ item }} && echo disable_ok ; fi
  register: output
  changed_when: "'disable_ok' in output.stdout"
  loop:
    - avahi-daemon
    - abrtd
    - abrt-ccpp

It produces 3 states:

  • service is absent or disabled already — ok
  • service exists and was disabled — changed
  • service exists and disable failed — failed

Upvotes: 5

sys0dm1n
sys0dm1n

Reputation: 879

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.

Upvotes: 6

Related Questions