I'm new to Ansible and couldn't figure out how to achieve this from the documentation: I have an inventory file like this:
example_site:
children:
...
example_hosts:
hosts:
h1:
ansible_host: "192.168.0.1"
h2:
ansible_host: "192.168.0.2"
Now I want to start a Gluster cluster there in a playbook:
tasks:
- name: Create a trusted storage pool
become: yes
gluster.gluster.gluster_peer:
state: present
nodes:
- "192.168.0.1"
- "192.168.0.2"
Is there a way to not hardcode this list of ip addresses? I tried node: groups['example_hosts']
, but that did not work.
How can I get a list of ip addresses from the inventory?
The IP addresses of hosts defined in your inventory can be accessed with the
ansible_host
variable, i.e.hostvars['h1']['ansible_host']
=> "192.168.0.1". Since you need the IP address of the hosts in that group as an array, we can iterate over the hosts ingroup['example_hosts']
, which is a list["h1", "h2"]
as well.In the below example, we create another variable with the list of IP address of hosts in
example_hosts
group:This gives the list of IP addresses in
cluster_hosts
:This variable can be passed to the
nodes
parameter of thegluster_peer
module: