title: How do I write an ansible handler that can run a task on failure?
body: <p>I want to use ansible 2.5.2 to perform some upgrade tasks and rollback to a previous install if they fail. I use notify on all config changes to prevent an upgrade if there are no changes. I initially thought to use <code>block:</code> and <code>rescue:</code> statements in the handler for that notify. </p>
  
  <p>However as this is not supported yet (<a href="https://github.com/ansible/ansible/issues/14270" rel="nofollow noreferrer">https://github.com/ansible/ansible/issues/14270</a>) I instead took the suggested workaround of including another task in the notify block, to end up with something equivalent to the following:</p>
  
  <pre><code>upgrade
  |-handlers
    main.yml
    - name: upgrade task
      include: upgrade.yml
  |-tasks
    main.yml
    - name: Update configuration 1
      template: src=conf.j2 dest={{ conf_dir }}/conf.conf
      notify: upgrade task
    - name: Update configuration 2
      template: src=conf2.j2 dest={{ conf_dir }}/conf2.conf
      notify: upgrade task
  
    upgrade.yml
    - block:
      - debug: msg="Starting upgrade"
      - name: Simulate failure of first of many upgrade tasks
        command: /bin/false
      rescue:
      - debug: msg="Upgrade failed, rolling back now"
      - name: Rollback deploy
        include: rollback.yml
      always:
      - debug: msg="Upgrade complete"
  
    rollback.yml
      ....
  </code></pre>
  
  <p>As expected this fails on:</p>
  
  <pre><code>RUNNING HANDLER [upgrade : Simulate failure of first of many upgrade tasks] 
  fatal: [hostname]: FAILED!
  </code></pre>
  
  <p>but no <code>Upgrade failed</code> or <code>Upgrade complete</code> is printed and the <code>rollback.yml</code> is not executed.</p>
  
  <p>The possibilities seems to be:</p>
  
  <ol>
  <li>There is an error in my tasks that is silently preventing the rescue block from running.</li>
  <li>There is an ansible bug which has not been raised yet with blocks in included plays.</li>
  <li>What I am trying to do is not supported.</li>
  </ol>
  
  <p>Can anyone spot an issue or give me some pointers on structuring this problem in a supported way? The only alternative I can think of is using a <code>listen</code> to group the handlers, mark them as changed but not failed when they fail, and have them notify the rollback task, but at first glance this seems like it would be extremely fragile.</p>