Reputation: 113
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]
Upvotes: 3
Views: 5109
Reputation: 1299
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
Upvotes: 1
Reputation: 4777
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}}"
Upvotes: 2