Hi all,
I’ve been looking into this for some time now, and I think I definitely can use some help here.
What I want is to set a variable from a task specific to one host from a group, with a value that is set dynamically by the task outcome.
Then next, I want to use this variable by another play, with more hosts from that same group.
e.g. :
group = { host_a, host_b, host_c }
Why can't do that?
You can in the second play also access the result variable directly like so
{{ hostvars['host_a']['result'] }}
True. And thanks for contributing.
I knew this. I think I oversimplified my testcase… Thing is, our inventory has many groups, where hosts can be member
of multiple groups… Here’s a modified testcase :
groupall = { host_a, host_b, host_c }
group1 = { host_a }
group2 = { host_b, host_c }
The playbook is started with the ‘–limit groupall’ argument.
Now, because of the groups, the second play cannot lookup ‘host_a’ in the hostvars, since it has no knowledge
about the hosts in ‘group1’…
Any ideas ?
Knowledge of members in group1 you find with groups['group1']
So this should work.
hostvars[groups['group1'][0]]['result']
Hi Kai,
you said :
Knowledge of members in group1 you find with groups[‘group1’]
hostvars[groups[‘group1’][0]][‘result’]
actually, the ‘group1’ group contains a lot of hosts… There is no quarantee
that the first entry in that array actually is the host that applies to my playbook.
Then I don't understand what you are trying to achieve, your testcase must be flawed.
Every host in group1 will run that task, so every host in the group will have a "result" variable set.
You must choose at some level who is going to be the "global" one.
OK, redefining my testcase then :
groupall = { host_a, host_b, host_c }
group1 = { host_x, host_y, host_a, host_z }
group2 = { host_b, host_c }
tasks:
tasks:
The playbook is started with the ‘–limit groupall’ argument.
Yes, every host in ‘group1’ will have access to the result.
What I want is to access that result in the other play ( for ‘group2’ ).
( BTW, I understand that the first play will only be executed on ‘host_a’ since that’s the only host that is in ‘groupall’…)
For now I’ll call it a playbook ‘global’ variable… Like an ‘extra_var’ , but then settable from within a play.
Thanks !
OK, so I looked at Ansible’s code, and I now know how to implement this. I tried my modification locally and
it works fine. It basically adds a module that adds an ‘extra_vars’ variable if it does not yet exist.
That way, any variable set on the commandline using the ‘–extra-vars’ argument cannot be overruled by the
playbook.
Now this scenario works :
Inventory :
group_all = { host_1, host_2, host_3 }
group_one = { host_1 }
group_two = { host_2, host3 }
Playbook ‘my_playbook.yml’ :