Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

--- interfaces:   vlan0:     ip: 127.0.0.1     mask: 255.255.255.0     state: true    vlan2:     ip: 127.0.1.1     mask: 255.255.255.0     state: true 

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

{% if interfaces.vlan1 %}  # and also I try {% if 'vlan1' in interfaces %} {{ interfaces.vlan1.ip }}; {% else %} {{ interfaces.vlan2.ip|default("127.0.0.1") }}; {% endif %}; 

But i have an error:

fatal: [127.0.0.1] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'dict object' has no attribute 'vlan1'", 'failed': True} 

I found that it have to be 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

>>> from jinja2 import Template >>> b = Template(""" ... {% if interfaces.vlan1 %} ... {{ interfaces.vlan1.ip }} ... {% else %} ... {{ interfaces.vlan2.ip|default("127.0.3.1") }} ... {% endif %}""") >>> b.render(interfaces={'vlan3':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.2.1\n' >>> b.render(interfaces={'vlan1':{'ip':'127.0.1.1'},'vlan2':{'ip':'127.0.2.1'}}) u'\n\n127.0.1.1\n' 
like image 635
Alex Avatar asked Oct 28 '15 20:10

Alex


People also ask

How do you check if a dict contains a key?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How does the Jinja2 template helps Ansible?

Ansible uses Jinja2 templating to enable dynamic expressions and access to variables and facts. You can use templating with the template module.

Is Jinja2 dynamic?

Jinja supports dynamic inheritance and does not distinguish between parent and child template as long as no extends tag is visited.


1 Answers

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

{% if interfaces.vlan1 is defined %} {{ interfaces.vlan1.ip }} {% else %} {{ interfaces.vlan2.ip|default("127.0.3.1") }} {% endif %} 

This combination works well.

like image 123
Alex Avatar answered Sep 22 '22 17:09

Alex