ansibleansible-template

Restart service when service file changes when using Ansible


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?


Solution

  • 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.