1

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
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
javadev
  • 19
  • 2

2 Answers2

1

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

  • inventory.ini
    [group_1]
    hostA a=true
    hostB b=true
    hostC a=true b=true c=true
    
  • and inventory.constructed.yml
    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
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
0

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!"
Ivan
  • 61
  • 1
  • 1
  • 6
  • is it possible to not write any host? What I expected is like a filter which allowes me to just add hosts with flags and don't change any other code. – javadev May 16 '23 at 12:50
  • @javadev check updated answer or this [similiar question](https://stackoverflow.com/questions/67029581/ansible-how-to-select-hosts-based-on-certain-attributes-and-use-their-ip-address) – Ivan May 16 '23 at 14:46