run_once + delegate_to: localhost + conditional

47 views
Skip to first unread message

aaldi

unread,
Sep 14, 2018, 9:54:51 AM9/14/18
to Ansible Project
I have a senario where I check for a condition on remote machines, if any of them fails the condition, I'll create a file locally on the ansible controller and move it to any machine that failed the condition.

Creating the file locally should only be done once, thus the command contains the keywords: `delegate_to: localhost` and `run_once: true`. But also the creation task is bounded by the `when` keyword (we don't need to create it if NONE of the machines need it, but we need to create it if at least ONE machine needs it).

Based on the description of run_once in the documentation, it is equivalent to: `when: inventory_hostname == webservers[0]` basically only applying to the first machine.

So instead of creating the file if ONE machine needs it, it will create the file only if the FIRST machine needs it. 
So in the senario where the second or third machine needs the file, the subsequent tasks will fail since they try to copy the file over, but the file doesn't exist since the first machine didn't need it.

Is there a correct way of doing this? Or is this a bug?

Brian Coca

unread,
Sep 18, 2018, 11:14:07 AM9/18/18
to Ansible Project
The issue is that you are making the test on the 'current' host, but
that is not mandated, you can use the data from any/all the hosts and
use a 'select' filter to create a list of hosts that pass that test ..
so if select(,,,)|length > 1 you have an 'any' host matching
condition.




--
----------
Brian Coca
Reply all
Reply to author
Forward
0 new messages