I am having issues fetching the value of ansible_user
under rhel
from the inventory file. Below are the few ways that I tried to fetch, everytime it says undefined rhel
. Any suggestions as to how to retrieve it?
- set_fact:
SSHUSER: "{{ hostvars.[rhel].ansible_user }}"
- set_fact:
SSHUSER: "{{ rhel.ansible_user }}"
---
all:
vars:
project: test
hosts:
children:
test_vm:
hosts: 10.10.10.4
example_vm:
hosts: 10.10.10.5
ubuntu:
children:
test_vm:
vars:
os: ubuntu
ansible_user: "testuser"
rhel:
children:
example_vm:
vars:
os: rhel
ansible_user: "exampleuser"
The rhel
you are referencing is a group, not a host -- a host may belong to multiple groups. The expression you'd want in order to achieve "the hostvars of some member of the group rhel" is the jinja2 expression: {{ hostvars[groups["rhel"][0]].ansible_user }}
Where groups["rhel"]
are the list of strings of ansible inventory hostnames, and if one presumes they all have an equivalent ansible_user
then it should be safe to just grab the first one, which is groups["rhel"][0]
or the more verbose but perhaps clearer groups["rhel"]|first
Then, we want the hostvars
for that host, not our own; since hostvars
is a dict[str, dict]
indexed by the ansible inventory hostname, we can plug that value into the hostvars
dict as hostvars[groups["rhel"][0]]
which is every hostvar, and then hostvars[groups["rhel"][0]].ansible_user
gives back the ansible_user
fact you requested