# conditional in template?

**URL:** <https://forum.ansible.com/t/conditional-in-template/17897>\
**Category:** Ansible Project\
**Created:** [April 2, 2015, 10:33pm UTC](https://forum.ansible.com/t/conditional-in-template/17897 "2015-04-02T22:33:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![J11](https://avatars.discourse-cdn.com/v4/letter/j/3bc359/32.png) [@J11](https://forum.ansible.com/u/J11)\
**Post date:** [April 2, 2015, 10:33pm UTC](https://forum.ansible.com/t/conditional-in-template/17897/1 "2015-04-02T22:33:06Z")

</div>

All,

I’m attempting to use a conditional in a template, without success. Specifically I’m trying to add an iptable rule that allows traffic sourced from eth1 on all hosts:

Below is the relevant portion of the template:

{% if ‘eth1’ in ansible\_interfaces %}  
{% if hostvars[host][‘ansible\_eth1’][‘ipv4’][‘address’] is defined %}  
-A INPUT -s {{ hostvars[host][‘ansible\_eth1’][‘ipv4’][‘address’] }} -j ACCEPT  
{% endif %}  
{% endif %}  
{% endfor %}

Unfortunately the playbook still errors out:

fatal: [test2] =\> {‘msg’: “AnsibleUndefinedVariable: One or more undefined variables: ‘dict object’ has no attribute ‘ipv4’”, ‘failed’: True}

This server does indeed have an eth1 interface but said interface does _not_ have an IP address in this particular case.

This “if x is defined” syntax seems to work fine in a “when:” conditional in the playbook, just not in the template itself.

Any thoughts on what I may be doing wrong and how to rectify this error / problem?

Many thanks!

---

<div class="post-metadata">

**Author:** ![James\_Cammarata](https://avatars.discourse-cdn.com/v4/letter/j/7c8e57/32.png) [@James\_Cammarata](https://forum.ansible.com/u/James_Cammarata)\
**Post date:** [April 6, 2015, 3:48pm UTC](https://forum.ansible.com/t/conditional-in-template/17897/2 "2015-04-06T15:48:41Z")

</div>

Hi. The “is defined” portion is failing because of the ‘ipv4’ subkey failure. You will have to do something like this:

{% if ‘ipv4’ in hostvars[host][‘ansible\_eth1’] and hostvars[host][‘ansible\_eth1’][‘ipv4’][‘address’] is defined %}

If that’s still not working, and ansible\_eth1 does have the ‘ipv4’ entry, then this is most likely a fact-gathering issue, where the targeted host hasn’t yet gathered facts. If so, you can make sure facts are gathered about all systems by adding a simple initial play to your playbook:

- hosts: all  
gather\_facts: yes

Hope that helps!
