# problem with jinja2 template accessing hostvars fields

**URL:** <https://forum.ansible.com/t/problem-with-jinja2-template-accessing-hostvars-fields/13754>\
**Category:** Ansible Project\
**Created:** [October 23, 2013, 4:48pm UTC](https://forum.ansible.com/t/problem-with-jinja2-template-accessing-hostvars-fields/13754 "2013-10-23T16:48:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kesten\_Broughton2](https://avatars.discourse-cdn.com/v4/letter/k/ecc23a/32.png) [@Kesten\_Broughton2](https://forum.ansible.com/u/Kesten_Broughton2)\
**Post date:** [October 23, 2013, 4:48pm UTC](https://forum.ansible.com/t/problem-with-jinja2-template-accessing-hostvars-fields/13754/1 "2013-10-23T16:48:04Z")

</div>

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  
&nbsp;&nbsp;&nbsp;template: src=hosts.j2 dest=/etc/hosts

TASK: [common | Template /etc/hosts using inventory default ipv4]

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan2](https://avatars.discourse-cdn.com/v4/letter/m/da6949/32.png) [@Michael\_DeHaan2](https://forum.ansible.com/u/Michael_DeHaan2)\
**Post date:** [October 23, 2013, 6:51pm UTC](https://forum.ansible.com/t/problem-with-jinja2-template-accessing-hostvars-fields/13754/2 "2013-10-23T18:51:25Z")

</div>

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)

---

<div class="post-metadata">

**Author:** ![Garrett\_Plasky](https://avatars.discourse-cdn.com/v4/letter/g/5f9b8f/32.png) [@Garrett\_Plasky](https://forum.ansible.com/u/Garrett_Plasky)\
**Post date:** [June 3, 2014, 11:12pm UTC](https://forum.ansible.com/t/problem-with-jinja2-template-accessing-hostvars-fields/13754/3 "2014-06-03T23:12:29Z")

</div>

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.”
