Skip to content

Instantly share code, notes, and snippets.

@tyrells
Last active October 19, 2023 20:53
Show Gist options
  • Save tyrells/0a79681de339237cb04c to your computer and use it in GitHub Desktop.
Save tyrells/0a79681de339237cb04c to your computer and use it in GitHub Desktop.
Ansible task to stop service even if it doesn't exist
# This task will stop and disable a service without failing if the service does not exist.
# Requires Ansible 1.4 or newer.
# Update Dec 2016: Have rewritten this for the latest version of ansible and put conditions for both Ubuntu and CentOS
- name: "disable unused services"
service: name={{item}} state=stopped enabled=no
register: command_result
failed_when: "unused_disable|failed and ('find' not in unused_disable.msg and 'found' not in unused_disable.msg)"
with_items:
- httpd
- sendmail
@djvdorp
Copy link

djvdorp commented Oct 10, 2014

On Ubuntu 14.04 X64 LTS 'cannot find' should be replaced by 'service not found'
Thanks a lot!

@jamesdmorgan
Copy link

Works like a charm. Thanks

@LTGIV
Copy link

LTGIV commented Feb 25, 2015

Is there a way to use a pattern for matching? That way 'cannot find' and 'service not found' are both covered in one failed_when clause to this task?

@csiluszyk
Copy link

NOTE: In Ansible v2.0 it'll be available must_exist option:

http://docs.ansible.com/ansible/service_module.html

@Hubbitus
Copy link

It seams must_exist disappeared...

@thedavidwhiteside
Copy link

Is must_exist coming back? I was really excited about it.

@kimegede
Copy link

kimegede commented Aug 3, 2016

Could also use must_exist ;)

@tanandy
Copy link

tanandy commented Jan 3, 2017

works when i replace

register: command_result
by
register: unused_disable

thanks

@gareththered
Copy link

Just for info - with Ansible v2.9 and later, you cannot use a jinja test as a filter. Consequently, to get this to work, replace unused_disable|failed with: unused_disable is failed

@MelonSmasher
Copy link

A combination of comments here got it working for me:

---
- name: Disable Metrics Utilites
  hosts: all
  tasks:
  - name: Stop and disable unused services
    service: name={{item}} state=stopped enabled=no
    register: unused_disable
    failed_when: "unused_disable is failed and ('find' not in unused_disable.msg and 'found' not in unused_disable.msg)"
    with_items:
      - metricbeat
      - auditbeat
      - telegraf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment