Ansible get hostname as defined in inventory
Asked Answered
M

2

20

In my inventory I define hosts like this:

 [server1]
 141.151.176.223

I am looking for a variable which keeps the server1 name, as I am using it to define server hostname.

inventory_hostname is set to 141.151.176.223 ansible_hostname as well as inventory_hostname_short is set to 148.

To workaround this problem I am setting my own variable like this:

 [server1]
 141.151.176.223 hostname=server1

but I am not satisfied with this approach.

Any ideas?

Mallorca answered 21/1, 2018 at 14:13 Comment(0)
M
32

Explanation

If the inventory file was defined this way:

[server1_group]
server1 ansible_host=141.151.176.223

Then you can access:

  • server1 with the inventory_hostname fact;

  • 141.151.176.223 with the ansible_host fact;

  • server1_group with group_names|first (group_names fact contains a list of all groups server belongs to, first selects the first element from that list).

Regardless of the above, ansible_hostname fact contains the host name as defined on the host itself (the value is set during facts gathering).


Solution

You should use a standard ansible_host declaration to point to the target's IP address and set the inventory hostname to however you want to refer to the server in Ansible playbooks.

In particular you can skip groups definition altogether and define just:

server1 ansible_host=141.151.176.223
Moro answered 21/1, 2018 at 23:46 Comment(2)
Thank you for this. I wasn't aware that I was using Ansible wrong. I've fixed my inventory :)Mallorca
if you could provide exact syntax how to access what would be really gratefulSpecialist
T
3

The [server1] declaration is the name of a group, not a host (even if you only assign a single host to that group).

As ansible allows a host to be placed in multiple groups, you can only get the names as an array: http://docs.ansible.com/ansible/latest/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts

So I think the workaround that you found is the way to go, unless you can use real host names instead of IP addresses (using DNS or just static hosts file).

Turnkey answered 21/1, 2018 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.