Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle changes to init scripts in Ansible?

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?

like image 388
hepabolu Avatar asked Jun 22 '14 11:06

hepabolu


2 Answers

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.

like image 155
andyhky Avatar answered Oct 17 '22 23:10

andyhky


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.

like image 1
hepabolu Avatar answered Oct 17 '22 21:10

hepabolu