Unable to access hostvars in template

71 views
Skip to first unread message

Gordon Ross

unread,
Dec 3, 2014, 12:04:35 PM12/3/14
to ansible...@googlegroups.com
According to the Ansible docs ( http://docs.ansible.com/faq.html#how-do-i-loop-over-a-list-of-hosts-in-a-group-inside-of-a-template ) You can put the following in a template:

{% for host in groups[’test_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}

But when I do that, I get:

TASK: [Template Test] *********************************************************
fatal: [srv.exmpale.com] => {'msg': "One or more undefined variables: 'dict object' has no attribute 'ansible_eth0'", 'failed': True}

If I put:

{% for host in groups['test_servers'] %}
{{ hostvars[host] }}
{% endfor %}

then I get a Python formatted output of all the facts.

Yet if I put in the template:

{{ hostvars[inventory_hostname]['ansible_eth0']['ipv4']['address'] }}

or

{{ hostvars['srv.exmpale.com']['ansible_eth0']['ipv4']['address'] }}

Then that works and I get the IP address in the file.

Google only reveals someone who had the same problem and gave up :-(

Thanks,

GTG
--
Gordon Ross

Jean-Philippe Caruana

unread,
Dec 3, 2014, 12:32:42 PM12/3/14
to ansible...@googlegroups.com
I had a helpful answer for that:

> ansible server -m setup -i production, should provide you the correct
info.
> I suspect one of your hosts does not have an ipv4 address assigned to
eth1.


I added a condition:

{% if hostvars[host]['ansible_eth1']['active'] %}

(replace eth1 by eth0 in your case)

see
https://groups.google.com/forum/#!msg/ansible-project/RS1Mvdfjk2k/plfaT1g7cN0J


hope this helps
Jean-Philippe Caruana
http://www.barreverte.fr

Reply all
Reply to author
Forward
0 new messages