Q: "hostvars can not get ansible_host"
A: ansible_host
is not included in hostvars
if it is not explicitly declared. ansible_host
is a Connection variable. It is used, for example, as a parameter of the ssh connection plugin
(see ansible-doc -t connection ssh
). It is needed if inventory_hostname
does not resolve. Very probably, any of your hosts don't have an ansible_host
explicitly set. This is causing the problem. If ansible_host
is not explicitly declared its value is set to inventory_hostname
.
For example
shell > grep test_11 hosts
test_11
- hosts: test_11
tasks:
- debug:
var: hostvars[inventory_hostname]['ansible_host']
- debug:
var: ansible_host
gives
TASK [debug] *************************************************************
ok: [test_11] =>
hostvars[inventory_hostname]['ansible_host']: VARIABLE IS NOT DEFINED!
TASK [debug] *************************************************************
ok: [test_11] =>
ansible_host: test_11
If you declare ansible_host
, for example, in the inventory
shell > grep test_11 hosts
test_11 ansible_host=10.1.0.61
the same playbook gives
TASK [debug] *************************************************************
ok: [test_11] =>
hostvars[inventory_hostname]['ansible_host']: 10.1.0.61
TASK [debug] *************************************************************
ok: [test_11] =>
ansible_host: 10.1.0.61
ansible_host: The ip/name of the target host to use instead of inventory_hostname.
A quick solution to the problem might be defaulting to inventory_hostname
, assuming ansible_host
is not needed, i.e. inventory_hostname
resolves. For example
{% for host in groups['all'] %}
server {{ host }} {{ hostvars[host]['ansible_host']|default(host) }}
{% endfor %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…