Check If Service Exists With Ansible


Answer :

See the service_facts module, new in Ansible 2.5.

- name: Populate service facts   service_facts: - debug:     msg: Docker installed!   when: "'docker' in services" 

Of course I could also just check if the wrapper script exists in /etc/init.d. So this is what I ended up with:

  - name: Check if Service Exists     stat: path=/etc/init.d/{{service_name}}     register: service_status    - name: Stop Service     service: name={{service_name}} state=stopped     when: service_status.stat.exists     register: service_stopped 

It would be nice if the "service" module could handle "unrecognized service" errors.

This is my approach, using the service command instead of checking for an init script:

- name: check for apache   shell: "service apache2 status"   register: _svc_apache   failed_when: >     _svc_apache.rc != 0 and ("unrecognized service" not in _svc_apache.stderr)  - name: disable apache   service: name=apache2 state=stopped enabled=no   when: "_svc_apache.rc == 0" 
  • check the exit code of "service status" and accept the exit code 0 when the output contains "unrecognized service"
  • if the exit code was 0, that service is installed (stopped or running)

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?