What is the difference between ansible_hostname vs inventory_hostname?
These two ansible internal variables sometimes confuse one for another but they're fundamentally different.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
ansible_hostname and ansible_fqdn
Read from the target machine hostname from the facts:
ansible_hostnameread the hostname from the facts collected during thegather_facts
- Same as the
uname -norhostnamecommand-line
- Need
gather_factsenabled, otherwise theansible_factsvariable would be unavailable to use in your playbook
- Same as hostname of the target host
- As this is based on the
gather_factsstep. ansible_hostname not available in ad-hoc command
inventory_hostname
Read from Ansible inventory or hosts files:
inventory_hostnameread the hostname from the inventory configuration or the hosts file. Could be different from the hostname configuration of the remote system. It could be only a name on the controller machine
inventory_hostnameis always available to use in your playbook.
- Could be different from the hostname of the target host
- Available for both playbook and ad-hoc command
Playbook
Let me show you the difference between ansible_hostname vs inventory_hostname vs ansible_fqdn internal variables in a simple Ansible Playbook.
code
- hostnames.yml
``yaml
---
- name: hostnames Playbook
hosts: all
gather_facts: true
tasks:
- name: print inventory_hostname
ansible.builtin.debug:
var: inventory_hostname
- name: print ansible_hostname
ansible.builtin.debug:
var: ansible_hostname
- name: print ansible_fqdn
ansible.builtin.debug:
var: ansible_fqdn
`
- inventory
`yaml
foo.example.com ansible_host=192.168.0.190
[all:vars]
ansible_connection=ssh
ansible_user=devops
ansible_ssh_private_key_file=~/.ssh/id_rsa
`
execution
``bash
ansible-pilot $ ansible-playbook -i ansible\ statements/inventory ansible\ statements/hostnames.yml
PLAY [hostnames Playbook] *
TASK [Gathering Facts]
ok: [foo.example.com]
TASK [print inventory_hostname] *
ok: [foo.example.com] => {
"inventory_hostname": "foo.example.com"
}
TASK [print ansible_hostname] *