problem with jinja2 template accessing hostvars fields

2,950 views
Skip to first unread message

Kesten Broughton

unread,
Oct 23, 2013, 12:48:04 PM10/23/13
to ansible...@googlegroups.com
Can anybody explain why I can access ansible_default_ipv4 in a task, but not in a jinja2 file?


 - debug: msg="{{ hostvars[inventory_hostname]['ansible_default_ipv4'] }}"
This gives an ipv4 address like 10.10.10.10

In roles/common/tasks/main.yml

 - name: Template /etc/hosts using inventory default ipv4
   template: src=hosts.j2 dest=/etc/hosts

TASK: [common | Template /etc/hosts using inventory default ipv4] ************* 
fatal: [Ubuntu_Cluster_02] => {'msg': "One or more undefined variables: 'dict object' has no attribute 'ansible_default_ipv4'", 'failed': True}

I checked with a dump.j2 template that all my hosts do have the ansible_default_ipv4 field.

Here is the hosts.j2

# {{ansible_managed}}
127.0.0.1 localhost
{% for host in groups['all'] %}

{{ hostvars[host]["ansible_default_ipv4"]["address"]   }}   {{ host }}

{%  endfor %}

Michael DeHaan

unread,
Oct 23, 2013, 2:51:25 PM10/23/13
to ansible...@googlegroups.com
I suspect you probably haven't talked to that host yet previously.

The solution would be to make sure you talk to the host in a previous play, even if that play contains no other facts than fact gathering.

(FWIW, fact caching is something we're looking to add in a future release)




--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Michael DeHaan <mic...@ansibleworks.com>
CTO, AnsibleWorks, Inc.
http://www.ansibleworks.com/

Garrett Plasky

unread,
Jun 3, 2014, 7:12:30 PM6/3/14
to ansible...@googlegroups.com
I discovered this "feature" today and found it rather perplexing. I've used the workaround of 'gather_facts: yes' to fix it in this case, but it would be nice to be able to pre-populate the hostvars array with playbook and/or command-line variables instead of having to rely on the fact gathering "hack."
Reply all
Reply to author
Forward
0 new messages