# Using playbook to start, stop or restart a service

**URL:** <https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324>\
**Category:** Ansible Project\
**Created:** [May 1, 2016, 8:49pm UTC](https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324 "2016-05-01T20:49:44Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rick\_O\_Shea](https://avatars.discourse-cdn.com/v4/letter/r/65b543/32.png) [@Rick\_O\_Shea](https://forum.ansible.com/u/Rick_O_Shea)\
**Post date:** [May 1, 2016, 8:49pm UTC](https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324/1 "2016-05-01T20:49:44Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Johannes\_Kastl](https://avatars.discourse-cdn.com/v4/letter/j/bbe5ce/32.png) [@Johannes\_Kastl](https://forum.ansible.com/u/Johannes_Kastl)\
**Post date:** [May 3, 2016, 4:34am UTC](https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324/2 "2016-05-03T04:34:02Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Uditha\_Desilva](https://avatars.discourse-cdn.com/v4/letter/u/f475e1/32.png) [@Uditha\_Desilva](https://forum.ansible.com/u/Uditha_Desilva)\
**Post date:** [May 3, 2016, 7:20am UTC](https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324/3 "2016-05-03T07:20:36Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![rup](https://avatars.discourse-cdn.com/v4/letter/r/71c47a/32.png) [@rup](https://forum.ansible.com/u/rup)\
**Post date:** [May 3, 2016, 3:36pm UTC](https://forum.ansible.com/t/using-playbook-to-start-stop-or-restart-a-service/21324/4 "2016-05-03T15:36:26Z")

</div>

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.
