Forcing handlers

Normally, when Ansible fails a host, it stops executing anything on that host. This means that any pending handlers will not be run. This can be undesirable, and there is a play control that will force Ansible to process pending handlers for failed hosts. This play control is force_handlers, which must be set to the Boolean true.

Let's modify our preceding example a little, in order to demonstrate this functionality. We'll remove our max_fail_percentage parameter and add a new first task. We need to create a task that will return successfully with a change. This is possible with the debug module, using the changed_when task control, as the debug module will never register a change otherwise. We'll revert our fail task conditional to our original ones, as well:

--- 
- name: any errors fatal 
  hosts: failtest 
  gather_facts: false 

tasks:
- name: run first
debug:
msg: "I am a change"
changed_when: true
when: inventory_hostname == play_hosts[-1]
notify: critical handler
- name: change a host
fail:
msg: "I am last"
when: inventory_hostname == play_hosts[-1]

Our third task remains unchanged, but we will define our critical handler:

  - name: never run
debug:
msg: "I should never be run"
when: inventory_hostname == play_hosts[-1]

handlers:
- name: critical handler
debug:
msg: "I really need to run"

Let's run this new play to show the default behavior of the handler not being executed. In the interest of reduced output, we'll limit execution to just one of the hosts. Note that, although the handler is referenced in the play output, it is not actually run, as evidenced by the lack of any debug message:

Now, we add the force_handlers play control and set it to true:

---
- name: any errors fatal
hosts: failtest
gather_facts: false
force_handlers: true

This time, when we run the playbook, we should see the handler run, even for the failed hosts:

Forcing handlers can be a runtime decision, as well, using the --force-handlers command-line argument on ansible-playbook. It can also be set globally, as a parameter in ansible.cfg.

Forcing handlers to run can be really useful for repeated playbook runs. The first run may result in some changes, but if a fatal error is encountered before the handlers are flushed, those handler calls will be lost. Repeated runs will not result in the same changes, so the handler will never run without manual interaction. Forcing handlers to execute attempts to ensure that those handler calls are not lost.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.23.127.197