I'm relatively new to Ansible and I've created a playbook that can install a Tomcat configuration on a 'bare' server. I'm wondering how to solve the problem of being able to update the init.d script while avoiding the stop the service at the start of the playbook when there is no change in the script. Here's the basic playbook:
- name: stop tomcat service
service: name=my_service state=stopped
- name: copy init.d script
template: src=script.j2 dest=/etc/init.d/my_service
- name: do other tasks here
- name: start tomcat service
service: name=my_service state=restarted
This playbook will always stop and start the service, even if there are no changes. What I want the playbook to do is only stop and start the service when there are actual changes.
I know I could use handlers (need to look into that more), but I need to stop the service using the OLD init.d script, before copying the NEW script. AFAIK the handlers respond to the result of a task AFTER the action has taken place, which would mean the new script is already copied over the old one and might prevent the service from stopping and restarting.
How do I handle that?
Any task that is set to notify a handler will do exactly that at the end of the play.
http://docs.ansible.com/playbooks_best_practices.html#task-and-handler-organization-for-a-role
- name: Copy init.d script
template: src=script.j2 dest=/etc/init.d/my_service
notify: start tomcat service
handlers:
- name: start tomcat service
service: name=my_service state=restarted
You may want to have a play to work with the old script with a handler that stops the services with the old script, and a different play copying the new script with handlers.
From what I've learned from the comments above, I guess the best configuration of this playbook should be something like the one below. I still don't get how to stop the service in time for the copy init script task to run, but only when the task will run.
- tasks:
- name: do various tasks here
notify: restart tomcat service
- name: stop tomcat service
service: name=tomcat state=stopped
when: {{ indicator_init_script_task_will_fire }}
- name: copy init.d script
notify: restart tomcat service
handlers:
- name: restart tomcat service
service: name=my_service state=restarted
I haven't found what the indicator should be. So feel free to update.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With