Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 696
Steve Crook Avatar asked Oct 20 '25 12:10

Steve Crook


1 Answers

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.

like image 72
techraf Avatar answered Oct 23 '25 07:10

techraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!