61

All I could find was this from the docs:

Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to the first period, without the rest of the domain.

Is there any actual difference between inventory_hostname and ansible_hostname variables in Ansible? If so, then which one should I use and when?

1 Answer 1

111
  • inventory_hostname - As configured in the ansible inventory file (eg: /etc/ansible/hosts). It can be an IP address or a name that can be resolved by the DNS
  • ansible_hostname - As discovered by ansible. Ansible logs into the host via ssh and gathers some facts. As part of the fact, it also discovers its hostname which is stored in ansible_hostname.

Which one should you use?

hostvars is a dictionary which has an entry for each inventory host. If you want to access host information, you need to use the inventory_hostname. If you want to use/print the name of the host as configured on the host, you should use ansible_hostname since most likely the IP will be used in the inventory file.

Important: To use ansible_hostname, you need to gather facts:

gather_facts: true

Otherwise, you will get a message that ansible_hostname is not defined.

"ansible_hostname": "VARIABLE IS NOT DEFINED!"

Try this with one host to understand the differences

  tasks:
    - debug: var=inventory_hostname
    - debug: var=ansible_hostname
    - debug: var=hostvars
3
  • 36
    inventory_hostname is an arbitrary name you set in inventory file. It doesn't need to be resolvable by DNS.
    – hedayat
    Commented Jan 2, 2019 at 17:45
  • 4
    But in that case you have to set ansible_host right?
    – lost
    Commented Feb 13, 2020 at 9:33
  • @lost yes, or set up ssh (~/.ssh/config) so it'll know how to connect there by name Commented Feb 14, 2022 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.