Restart service when service file changes when using Ansible

onknows picture onknows · Aug 20, 2019 · Viewed 12.7k times · Source

I am creating a systemd service using template module

---
- name: Systemd service
  template:
    src: sonar.unit.j2
    dest: /etc/systemd/system/sonarqube.service
  when: "ansible_service_mgr == 'systemd'" 

The contents of the sonarqube.service can change of course. On change I want to restart the service. How can I do this?

Answer

dubioushencho picture dubioushencho · Aug 20, 2019

There are two solutions.

Register + When changed

You can register template module output (with its status change),

register: service_conf

and then use when clause.

when: service_conf.changed

For example:

---
- name: Systemd service
  template:
    src: sonar.unit.j2
    dest: /etc/systemd/system/sonarqube.service
  when: "ansible_service_mgr == 'systemd'" 
  register: service_conf

- name: restart service
  service:
    name: sonarqube
    state: restarted
  when: service_conf.changed

Handler + Notify

You define your restart service task as handler. And then in your template task you notify the handler.

tasks:
  - name: Add Sonarqube to Systemd service
    template:
      src: sonar.unit.j2
      dest: /etc/systemd/system/sonarqube.service
    when: "ansible_service_mgr == 'systemd'"
    notify: Restart Sonarqube
  - …

handlers:
  - name: Restart Sonarqube
    service:
      name: sonarqube
      state: restarted

More info can be found in Ansible Doc.

Difference between those 2?

In the first case, the service will restart directly. In the case of the handler the restart will happen at the end of the play.

Another difference will be, if you have several tasks changes that need to restart of your service, you simply add the notify to all of them.

  • The handler will run if any of those task get a changed status. With the first solution, you will have to register several return. And it will generate a longer when clause_1 or clause_2 or
  • The handler will run only once even if notified several times.