How to include a host group into another host group depending on a host boolean variable?
[group-1]
hostA a=true
hostB b=true
hostC a=true b=true c=true
[group-a]
# I expect here hostA and hostC due to a=true
How to include a host group into another host group depending on a host boolean variable?
[group-1]
hostA a=true
hostB b=true
hostC a=true b=true c=true
[group-a]
# I expect here hostA and hostC due to a=true
You could use a constructed inventory along your normal inventory for this use case.
As pointed in the documentation, a constructed inventory allows you to
uses Jinja2 to construct vars and groups based on existing inventory
So with the inventories
[group_1]
hostA a=true
hostB b=true
hostC a=true b=true c=true
plugin: ansible.builtin.constructed
groups:
group_a: a
group_b: b
group_c: c
We can then run any Asnible command specifying those two:
ansible-inventory --graph \
--inventory inventory.ini \
--inventory inventory.constructed.yml
Which will yield
@all:
|--@ungrouped:
|--@group_1:
| |--hostA
| |--hostB
| |--hostC
|--@group_a:
| |--hostA
| |--hostC
|--@group_b:
| |--hostB
| |--hostC
|--@group_c:
| |--hostC
You can build host inventory in task:
- add_host:
groups: group-a
hostname: '{{ item[0] }}'
when: item.a == True
with_items: "{{ groups['group-1'] }}"
Another solution would be group hosts with same values, in this case a=true
by ansible module group_by
:
- hosts: all
gather_facts: false
tasks:
- name: Group hosts by variable 'a'
group_by:
key: "new_hosts_group_{{ a|default() }}"
- hosts: new_hosts_group_true
gather_facts: false
tasks:
- run_once: true
debug:
var: groups.new_hosts_group_true
- debug:
msg: "Hello, World!"