Python 检查 ansible 上 Jinja2 模板中的字典中是否存在键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33400771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:17:55  来源:igfitidea点击:

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

pythontemplatesdictionaryjinja2ansible

提问by Alex

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

我在 ansible 中有一个带有所有接口的 dict 的 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 vlan1if ok put to template value vlan1.ipelse put vlan2.ip.

我想检查 dict 是否有一个键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 foundthat 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 vlan1it works fine. Ansible version 1.9.2

发现它必须在 Jinja2 中工作,但它似乎在 ansible 中不起作用。也许有人有另一种方法来解决这个问题?当我定义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'

采纳答案by Alex

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

答案很简单,它显示在 ansible 错误消息中。首先,我需要检查是否定义了 var。

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

This combination works well.

这种组合效果很好。

回答by larsks

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

检查字典中是否存在键的最佳方法(在任何 Jinja2 上下文中,而不仅仅是在 Ansible 中)是使用in运算符,例如:

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