10

In an Ansible playbook, I'd like to restart a service after updating config file, but only if it was already running.

I do not want to control the state of the service with ansible, only restart it if it was previously started.

I could use a custom command for that, but it wouldn't be portable across different service management systems (upstart/systemd/sysvinit/openrc...) as ansible's service module is.

Thank you for any tips.

Beli
  • 268
  • 1
  • 2
  • 6

2 Answers2

5

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.

Mxx
  • 2,362
  • 2
  • 28
  • 40
  • Yes, I could to do it using a handler with "when" condition to restart the service. My only problem is a platform independent way how to detect if a service is already running without modifying it's state, like with the "service" module. – Beli Feb 25 '15 at 14:42
  • Currently `service` module can not do that. You could accomplish this by checking if the desired process exist with `shell`/`command` execution of ps or stat checking for presence of run/pid file. – Mxx Feb 25 '15 at 16:19
  • Thank you for naming the possibilities, I'll consider this as the correct answer. I'll also look into the `service` module and maybe propose an update or even submit a patch. – Beli Feb 25 '15 at 20:26
3

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.

slm
  • 7,615
  • 16
  • 56
  • 76