ansible only disable service if installed

Shell
- 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

Source

Also in Shell: