Ansible: Restart Service Only If It Was Running
Answer :
Register a variable when config is updated. Register another variable when you check if a service is running. Call service restart handler only if both variables are true.
As for specifics of various OS, you could have conditional execution based on family/distribution from host facts.
Ansible's service:
module doesn't provide a mechanism for checking if a service is already running or not. Therefore you'll have to resort to using something like this via the shell:
module to determine first if the service is running.
Example
Here I'm detecting whether WebSphere or Tomcat8 are running, and then restarting the appropriate service based on its status.
--- # handles tomcat8 - name: is tomcat8 already running? shell: service tomcat8 status warn=false register: _svc_tomcat8 failed_when: _svc_tomcat8.rc != 0 and ("unrecognized service" not in _svc_tomcat8.stderr) ignore_errors: true - name: restart tomcat8 if running service: name=tomcat8 state=restarted when: "_svc_tomcat8.rc == 0" # handles WAS - name: is WebSphere already running? shell: service Node01_was.init status warn=false register: _svc_websphere failed_when: _svc_websphere.rc != 0 and ("unrecognized service" not in _svc_websphere.stderr) ignore_errors: true - name: restart WebSphere if running service: name=Node01_was.init state=restarted when: "_svc_websphere.rc == 0" # vim:ft=ansible:
To only invoke the restart if a specific file's been updated, you can use a register:
on your copy:
or template:
tasks to save the state of whether the file was updated. The results of this register:
can then be incorporated as part of the when:
on the service: name=XXXX state=restarted
task.
Comments
Post a Comment