Graham Nicholls
Graham Nicholls

Reputation: 561

Ansible: notify handler for block of multiple tasks

Rather than add a notify: statement to each task in a role, I'd like to have any of the tasks notify the handler on a change - something like this:

block:    
- name: "001 | do something"
  debug: "blah"
- name: "002 | do something else"
  module: "blah"    
notify: "restart webserver"

However, Ansible reports that

notify is not a valid attribute for a block.  

This would be really useful - and, I'd argue, more readable. I want to restart the webserver if I changed the config, or if I installed a new module; upgraded some depending package, etc.

In response to a comment, I'm not asking for a block in a handler, but for a notify to apply to a block. Essentially, I want to notify a handler on any change made by any of the tasks in a role. I take the point that blocks don't have a changed status, which explains why it doesn't work. It'd be nice if the changed status was inherited by the block so that the handler could be notified at the task or the block level.

Upvotes: 2

Views: 3341

Answers (1)

U880D
U880D

Reputation: 12064

According Playbook Keywords, above Ansible v2.9 a block can use

notify List of handlers to notify when the task returns a changed=True status.

- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - block:

    - name: Show message
      shell:
        cmd: 'echo "Hello."'
      changed_when: true

    notify: hanlder

  handlers:

  - name: handler
    debug:
      msg: "Here I am."

Further Q&A

Further References

Upvotes: 4

Related Questions