Referring to the value part of Ansible inventory entry

76 views Asked by At

If I have a following entry in my Ansible hosts file:

[dbserver]
myserver

Then elsewhere in my task code I can refer to myserver as {{ groups['dbserver'][0] }} to get the hostname dynamically. Works great.

Now - similar scenario. Say I changed the hosts file to:

[dbserver]
db1 ansible_host=myserver ansible_user=myuser

What I found out that {{ groups['dbserver'][0] }} will now return "db1" and it seems to be a plain string. But what if I need to refer to both the actual hostname "myserver" and also need to know the user "myuser". How do I access these values?

1

There are 1 answers

1
techraf On BEST ANSWER

ansible_host and ansible_user are defined for a specific hosts, so they are accessible with hostvars:

- debug:
    var: hostvars['db1']['ansible_host']
- debug:
    var: hostvars['db1']['ansible_user']