Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: disable service only if present

Tags:

ansible

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.

like image 672
Petr Avatar asked Oct 27 '17 12:10

Petr


2 Answers

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.

like image 158
sys0dm1n Avatar answered Nov 15 '22 09:11

sys0dm1n


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
like image 27
stacker-baka Avatar answered Nov 15 '22 07:11

stacker-baka