Using ansible facts with when or only_if

Hello all!

I am trying to use ansible fact names (mainly group_names) with both when_string and only_if, but am hitting a road block. It seems to me that if I run a playbook using a child group like foo:children but in my play book I call out when_string or only_if for bar1 and bar2 groups (children of foo:children) the plays do not get run against them. Is this not an intended method for usage of when and only_if?

Dylan Silva wrote:

Hello all!

I am trying to use ansible fact names (mainly group_names) with both
when_string and only_if, but am hitting a road block. It seems to me that
if I run a playbook using a child group like foo:children but in my play
book I call out when_string or only_if for bar1 and bar2 groups (children
of foo:children) the plays do not get run against them. Is this not an
intended method for usage of when and only_if?

group_names should work fine, we'd have to see your playbook and inventory to
really be able to say much more. Note though that if you are targeting
different hosts, you really should have multiple plays doing so, that is what
hosts: is for.

Daniel

Thanks for the clarification. Unfortunately, something is going wrong with my playbook then, and I think I know the problem.

So the command I am running is

ansible-playbook /opt/ansible-playbooks/application/management/setup.yml --extra-vars=“hosts=application1” --verbose

My playbook has the following in it:

No, using a group includes child groups, I don’t think you can pass hosts that way.

Try this in playbook

  • hosts: $target

Then use -e ‘target=application1’

Brian Coca

For one, it's "only_if: 'appApp' in $group_names" if you *did* want to
do that, because group_names is an array, and not a string.

But, really, this is not the way ansible likes to do things.

It really loves this (as Daniel said):

hosts: appApp
tasks:
   - ...

hosts: appDb
tasks:
   - ...

Groups are already a hosts slicing mechanism (it's what they were made
for), so it makes it much simpler that way. only_if only exists for
the weird corner cases, if you find it in your playbooks, you should
really ask if it needs to be there.

If you do have to slice hosts up by arbitrary discovered criteria
(like OS type), the group_by module is also excellent for this.

--Michael

Great, this makes sense to me now! Thanks for the awesome suggestions!