Using Ansible to stop service that might not exist


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:

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

Trying with command module:

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?


The following will register the module output in service_stop; if the module execution’s standard output does not contain "Could not find the requested service" AND the service fails to stop based on return code, the module execution will fail. Since you did not include the entire stack trace I am assuming the error you posted is in the standard output, you may need to change slightly based on your error.

Leave a Reply