I am trying to get the ansible_fqdn
from all hosts in a group with something in a template with something like this
{% for host in groups.all %}
{{ hostvars[host].ansible_fqdn }}
{% endfor %}
Or using:
{% for host in query('inventory_hostnames', target) | map('extract', hostvars, 'inventory_hostname') %}
{{ hostvars[host].ansible_fqdn }}
{% endfor %}
In all cases I get:
"AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_fqdn'"
I do notice that if I just "print/write":
{{ hostvars[host] }}
The ansible_fqdn
is within facter_networking
, but also trying:
{{ hostvars[host][facter_networking].fqdn }}
or
{{ hostvars[host][facter_networking].fqdn }}
I get:
fatal: [10.25.176.10]: FAILED! => {
"changed": false,
"msg": "AnsibleUndefinedVariable: ansible.vars.hostvars.HostVarsVars object has no element {
'domain': 'test-x',
'fqdn': 'TEST-X.example.org',
'hostname': 'TEST-X',
'interfaces': {
'ens192': {
'bindings': [{
'address': '10.25.176.10',
'netmask': '255.255.254.0',
'network': '10.25.176.0'
}, {
'address': '10.25.177.226',
'netmask': '255.255.252.0',
'network': '10.25.176.0'
}],
'ip': '10.25.176.10',
'mac': '00:50:56:8f:ce:ca',
'mtu': 1500,
'netmask': '255.255.254.0',
'network': '10.25.176.0'
},
'lo': {
'bindings': [{
'address': '127.0.0.1',
'netmask': '255.0.0.0',
'network': '127.0.0.0'
}],
'ip': '127.0.0.1',
'mtu': 65536,
'netmask': '255.0.0.0',
'network': '127.0.0.0'
}
},
'ip': '10.25.176.10',
'mac': '00:50:56:8f:ce:ca',
'mtu': 1500,
'netmask': '255.255.254.0',
'network': '10.25.176.0',
'primary': 'ens192'
}
}
If I use:
{{ hostvars[host].facter_networking }}
I get:
"msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'facter_networking'
The data is there but any idea about how could I extract it?
This is the playbook:
- name: Gathering info
action: setup
- name: Create .pgpass
template:
src: pgpass.j2
dest: /home/postgres/.pgpass
owner: postgres
group: postgres
mode: 0600
The Ansible facts gathered for the hosts can be accessed from within the ansible_facts
dictionary. So, to access a host's fqdn
, you would have to access hostvars[host]['ansible_facts']['fqdn']
.
Since we are iterating over groups['all']
, just make sure that the gather facts task is running on - hosts: all
as well.
So, using the above method, the template could look like this:
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['fqdn'] }}
{% endfor %}
Note that the ansible_
prefix is not required, i.e. fqdn
instead of ansible_fqdn
.