Check if key exists in a dict in Jinja2 template on ansible

Question:

I have a host_var in ansible with dict with all interfaces:

And I want to check if dict has a key vlan1 if ok put to template value vlan1.ip else put vlan2.ip.

But i have an error:

I found that it have to re work in Jinja2 but it seems to doesn’t work in ansible. Maybe someone have another way for solving this problem?
When I define vlan1 it works fine. Ansible version 1.9.2

I was trying to reproduce it in python and have no error if my dictionary have not key vlan1. thanks to @GUIDO

Answer:

The answer is simple and it showed on ansible error message. First of all I need to check if var is defined.

This combination works well.

Leave a Reply