Running destructive tasks only once

Destructive tasks come in many flavors. They can be one-way tasks that are extremely difficult to roll back, one-time tasks that cannot be rerun easily, or race condition tasks that, if performed in parallel, would result in catastrophic failure. For these reasons and more, it is essential that these tasks be performed only once, from a single host. Ansible provides a mechanism to accomplish this by way of the run_once task control.

The run_once task control will ensure that the task only executes a single time from a single host, regardless of how many hosts happen to be in a play. While there are other methods to accomplish this goal, such as using a conditional to make the task execute only on the first host of a play, the run_once control is the most simple and direct way to express this desire. Additionally, any variable data registered from a task controlled by run_once will be made available to all hosts of the play, not just the host that was selected by Ansible to perform the action. This can simplify later retrieval of the variable data.

Let's create an example playbook to demonstrate this functionality. We'll reuse our failtest hosts that were created in an earlier example, in order to have a pool of hosts, and we'll select two of them by using a host pattern. We'll do a debug task set to run_once and register the results, then we'll access the results in a different task with a different host:

--- 
- name: run once test 
  hosts: failtest[0:1] 
  gather_facts: false 
 
  tasks: 
  - name: do a thing
debug:
msg: "I am groot"
register: groot
run_once: true

- name: what is groot
debug:
var: groot
when: inventory_hostname == play_hosts[-1]

When we run this play, we'll pay special attention to the hostnames listed for each task operation:

We can see that the do a thing task is executed on the failer01 host, while the what is groot task, which examines the data from the do a thing task, operates on the failer02 host .

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

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