Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ansible to stop service that might not exist

Tags:

ansible

I am using Ansible 2.6.1.

I am trying to ensure that certain service is not running on target hosts. Problem is that the service might not exist at all on some hosts. If this is the case Ansible fails with error because of missing service. Services are run by Systemd.

Using service module:

  - name: Stop service
    service:
      name: '{{ target_service }}'
      state: stopped

Fails with error Could not find the requested service SERVICE: host

Trying with command module:

 - name: Stop service
   command: service {{ target_service }} stop

Gives error: Failed to stop SERVICE.service: Unit SERVICE.service not loaded.

I know I could use ignore_errors: yes but it might hide real errors too.

An other solution would be having 2 tasks. One checking for existance of service and other that is run only when first task found service but feels complex.

Is there simpler way to ensure that service is stopped and avoid errors if the service does not exists?

like image 555
Madoc Comadrin Avatar asked Aug 09 '18 11:08

Madoc Comadrin


1 Answers

I'm using the following steps:

- name: Get the list of services
  service_facts:

- name: Stop service
  systemd:
    name: <service_name_here>
    state: stopped
  when: "'<service_name_here>.service' in services"

service_facts could be called once in the gathering facts phase.

like image 115
Nazar Avatar answered Nov 01 '22 04:11

Nazar