Get Ansible ongoing notify list

1.1k views Asked by At

I'm looking for a way to get the list (possibly an ansible system variable) that would contain current handler notifications triggered by a playbook.

In other words, at some point in a role, I would like to add a "when" condition to a task that would test if a "restart notification" has not been sent yet -> do this task when restart is not in the notification list

Any idea ?

Thanks a lot!

3

There are 3 answers

0
Marc-Antoine On BEST ANSWER

I finally came to a solution, quite acceptable, using facts.

I use a handler to set a fact and another one to perform the restart. I associate both of them with the listen parameter to the same notification.

Besides, a reload handler performs the reload only when that fact is not defined or set to false.

- name: Register restart Logstash
  set_fact:
    restart_notified: true
  listen: "Restart Logstash"

- name: Restart Logstash service
  systemd:
    name: logstash
    daemon_reload: true
    state: restarted
  listen: "Restart Logstash"

- name: Reload Logstash
  systemd:
    name: logstash
    daemon_reload: true
    state: reloaded
  when: restart_notified is not defined or not restart_notified

I then use where needed, either Restart Logstash or Reload Logstash, and only one is performed, restart or reload, but never both.

1
larsks On

Taking a step back, it seems odd that you're in a situation in which you need to restart something in this fashion. If you haven't made any changes, why restart it? And if you have made changes, why not register the notification on whatever task is making the changes?

In any case, for what you want to do it seems the easiest solution is just to raise a notification:

- debug:
    msg: ensure that handler myhandler is notified
  changed_when: "force_change|default('false')|bool"
  notify: myhandler

This will register a notification for myhandler, and it doesn't matter if a previous task has registered a notification or not: in either case, the myhandler handler will be triggered once at the end of the play.

0
simohe On

Similar solution, with register instead of set_fact.

tasks:
 - name: some tasks, which maybe trigger "restart notification"
   # ...
 - name: trigger reload handler always
   debug:
     msg: always trigger handler
   changed_when: true
   notify: reload notification

handlers:
 - name: restart notification
   debug:
   register: restartNotificationHandler 
 - name: reload notification
   debug:
   when: restartNotificationHandler is not defined or restartNotificationHandler is skipped

for how to trigger a handler always, see https://serverfault.com/questions/617548/always-trigger-handler-execution-in-ansible