Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible get hostname as defined in inventory

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?

like image 260
Tomasz Raganowicz Avatar asked Jan 21 '18 14:01

Tomasz Raganowicz


1 Answers

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
like image 124
techraf Avatar answered Sep 25 '22 09:09

techraf