Using playbook to start, stop or restart a service

We have host groups whose service states we wish to automate.

  • name manage service
    service: name=foo state={{state}}

As near as we can tell this is the only way to automate a playbook to start, stop, restart, enable, disable or status a service is to pass a variable on the command line:

ansible-playbook foo-service.yml -e state=started

Is this best practice?

I would say putting these into the handler section of your
role/playbook would be preferable, so you only restart the service if
something has changed. Unless you want to force the restart.

Remember ansible is idempotent, so starting a service that is already
started does not harm, but does not restart it either.

Johannes

The variable can be defined however you wish – I’m not quite sure why you think it can only be passed from the command line?

On the other hand, if all you want to do is to start a service from the command line, you can invoke the service module via the ansible command itself:

ansible -m service -e ‘name=foo state=started’

without having to create a playbook to do it.

But using the service module isn’t quite that simple, right? You have to set up your init script to identify the services that the module would call. That’s where I’m at currently.