Search code examples
ansiblesystemd

Ansible handlers - exclusive restart or reload


I have a number of Ansible roles that notify handlers to either restart or reload systemd services. If a restart is notified, there's obviously no need to do a reload of the same service and trying to do both can lead to failure as the reload comes too quickly after the restart. Is there a way to configure the handlers so that the reload task only triggers if a restart task hasn't run?

Below is an example of my current restart/reload handler.

    - name: Restart foo service
      systemd:
        name: foo
        daemon_reload: yes
        state: restarted
      become: yes

    - name: Reload foo service
      systemd:
        name: foo
        daemon_reload: yes
        state: reloaded
      become: yes

Solution

  • You can notify a handler from a handler, so you can implement what you want, for example in this way (or using logical operators):

        - name: Restart foo service
          set_fact:
            foo_state: restarted
          changed_when: true
          notify: Reload foo service
        
        - name: Reload foo service
          systemd:
            name: foo
            daemon_reload: yes
            state: "{{ foo_state | default('reloaded') }}"
          become: yes
    

    Handler names are a matter of preference, I'm leaving them as they are.