Ansible get hostname as defined in inventory

Question:

In my inventory I define hosts like this:

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:

but I am not satisfied with this approach.

Any ideas?

Answer:

Explanation

If the inventory file was defined this way:

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:

Leave a Reply