Using Ansible to stop service that might not exist

2019-07-06 02:28发布

问题:

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?

回答1:

IMHO there isn't simpler way to ensure that service is stopped. Ansible service module doesn't check service's existence. Either (1) more then one task, or (2) command that check service's existence is needed. The command would be OS specific. For example for FreeBSD

command: "service -e | grep {{ target_service }} && service {{ target_service }} stop"


标签: ansible