title: Check if service exists with Ansible
body: <p>I have an Ansible playbook for deploying a Java app as an init.d daemon.</p>
  
  <p>Being a beginner in both Ansible and Linux I'm having trouble to conditionally execute tasks on a host based on the host's status.</p>
  
  <p>Namely I have some hosts having the service already present and running where I want to stop it before doing anything else. And then there might be new hosts, which don't have the service yet. So I can't simply use <code>service: name={{service_name}} state=stopped</code>, because this will fail on new hosts.</p>
  
  <p>How I can I achieve this? Here's what I have so far:</p>
  
  <pre><code>  - name: Check if Service Exists
      shell: "if chkconfig --list | grep -q my_service;   then echo true;   else echo false; fi;"
      register: service_exists
  
  # This should only execute on hosts where the service is present
    - name: Stop Service
      service: name={{service_name}} state=stopped
      when: service_exists
      register: service_stopped
  
  # This too
    - name: Remove Old App Folder
      command: rm -rf {{app_target_folder}}
      when: service_exists
  
  # This should be executed on all hosts, but only after the service has stopped, if it was present
    - name: Unpack App Archive
      unarchive: src=../target/{{app_tar_name}} dest=/opt
  </code></pre>