ansibleconditional-statementsnotify

How do you notify a handler in Ansible based solely on a conditional?


I would like to notify a handler in my role by doing something like this:

- name: Notify handler
  notify: my_handler
  when: this_thing_is_true|bool

But Ansible just whines:

ERROR! no module/action detected in task.

I have tried various wedges, such as:

- name: Notify handler
  meta: noop
  notify: my_handler
  when: this_thing_is_true|bool

But that similarly whines:

[WARNING]: noop task does not support when conditional

Any suggestions?


Solution

  • Please mind that running a task is not enough for an handler to be notified, you also need a task that creates a changed result.

    You can achieve a change result on any task with the help of the changed_when option in Ansible.
    Then, doing a simple debug could be an option.

    The other ideas I had, but that did not really made sense in the end:

    Given the playbook:

    - hosts: localhost
      gather_facts: no
      vars:
        this_thing_is_true: true
    
      tasks:
        - debug:
            msg: 'Notifying handlers'
            # var: this_thing_is_true 
            # ^-- might be an alternative option to msg:
          changed_when: this_thing_is_true  
          notify: 
            - me 
    
      handlers:
        - name: me
          debug:
            msg: 'I have been notified'
    

    Gives the recap:

    PLAY [localhost] **************************************************
    
    TASK [debug] ******************************************************
    changed: [localhost] => 
      msg: Notifying handlers
    
    RUNNING HANDLER [me] **********************************************
    ok: [localhost] => 
      msg: I have been notified