3
host1: abc
host2: xyz

host1 and host2 are listed under test-hosts

[test-hosts]
abc
xyz

When i debug for inventory_hostnames, i see them like below

    > TASK [debug inventory_hostname]
    > ************************************************************************************************************************************************************************* 
ok: [abc] => {
    >     "inventory_hostname": "abc" } 
ok: [xyz] => {
    >     "inventory_hostname": "xyz" }

Is there any way we can gather inventory_hostname's like a list by assigning it to a variable.

Expected result:

exp_result: [abc, xyz]
ilias-sp
  • 6,135
  • 4
  • 28
  • 41
munna
  • 103
  • 2
  • 9

2 Answers2

2

You can use groups['test-hosts'] to get those hosts as a list.

For example:

---
- hosts: all
  gather_facts: false
  tasks:
    - set_fact:
        host_list: "{{ groups['test-hosts'] }}"
    - debug:
        msg:  "{{host_list}}"
Alassane Ndiaye
  • 4,427
  • 1
  • 10
  • 19
1

You can also use the variable inventory_hostnames if you want to select multiple groups or exclude groups with patterns.

In these examples, we're selecting all hosts except ones in the www group.

Saving the list of hosts as a variable for a task:


- debug:
    var: hostnames
  vars:
    hostnames: "{{ query('inventory_hostnames', 'all:!www') }}"

You can also use the lookup plugin to loop over the hosts that match the pattern. From the docs:

- name: show all the hosts matching the pattern, i.e. all but the group www
  debug:
    msg: "{{ item }}"
  with_inventory_hostnames:
    - all:!www

Dash
  • 1,191
  • 7
  • 19