I have a jinja2 template, and I'm trying to loop through a host group, and insert the ipv4 address of all the hosts in my template. But I'm getting an error when I do it, even though the way I'm doing it is the way every post and article suggest it should be done.
Here's the template that's producing the error:
{% if groups['linux-hosts'] %}
{% for item in groups['linux-hosts'] %}
define host {
use generic-host-normal
host_name {{ item }}
alias {{ item }}
address {{ hostvars[item].ansible_default_ipv4.address }}
}
{% endfor %}
{% endif %}
And the error I'm getting is:
failed: [server] (item=servers.cfg) => {"changed": false, "item": "servers.cfg", "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'ansible_default_ipv4'"}
If I don't use the variable 'item' in the square brackets, but instead specify a specific host from the inventory, Ansible is able to get the ipv4 address. Example ('server' is the name of a host from my inventory):
{{ hostvars['server'].ansible_default_ipv4.address }}
It's because you are missing the gather_facts: yes
or an equivalent - setup:
task in your playbook; those facts don't magically appear unless requested, which happens by default, but one can certainly switch off through gather_facts: no
A simple test will show what I mean:
- hosts: all
gather_facts: yes
tasks:
- debug: var=ansible_default_ipv4 verbosity=0
and then change gather_facts: no
and observe the kaboom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With