检查Jinja2模板中是否存在一个关键字。

时间:2022-10-19 20:48:14

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

我有一个host_var,它与所有接口的命令是一致的:

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

我想要检查一下,如果ok的模板值是vlan1,它是否有一个键vlan1。其他ip 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

我发现它必须在Jinja2中工作,但它似乎并不能在anable中工作。也许有人可以用另一种方法来解决这个问题?当我定义vlan1时,它运行良好。Ansible 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

我试着用python复制它,如果我的字典没有键vlan1没有错误。由于@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'

2 个解决方案

#1


19  

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

答案很简单,它显示了一个错误信息。首先,我需要检查var是否被定义。

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

This combination works well.

这种组合是有效的。

#2


6  

The best way to check if a key exists in a dictionary (in any Jinja2 context, not just with Ansible) is to use the in operator, e.g.:

检查字典中是否存在键的最好方法(在任何Jinja2环境中,而不仅仅是在anable中)是使用in操作符,例如:

{% if 'vlan1' in interfaces %}
{{ interfaces.vlan1.ip |default(interfaces.vlan2.ip) }};
{% endif %}

#1


19  

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

答案很简单,它显示了一个错误信息。首先,我需要检查var是否被定义。

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

This combination works well.

这种组合是有效的。

#2


6  

The best way to check if a key exists in a dictionary (in any Jinja2 context, not just with Ansible) is to use the in operator, e.g.:

检查字典中是否存在键的最好方法(在任何Jinja2环境中,而不仅仅是在anable中)是使用in操作符,例如:

{% if 'vlan1' in interfaces %}
{{ interfaces.vlan1.ip |default(interfaces.vlan2.ip) }};
{% endif %}