如果变量存在和不存在则有条件

Conditional if the variable exists and does not exist

我有这样的 YAML 数据:

peers:
  eth1:
    hostname: host-01
    state: Idle
  eth2:
    hostname: host-02
    state: Established
  eth3:
    hostname: host-03
    state: Established
ping_to:
  host-02: success
  host-03: success  

对于 jinja2,我想定义这样的东西:

{% for key, value in peers.iteritems() %}
{% for key2, value2 in ping.iteritems() %}
{% if value.hostname is exist in key2 %}
ping is success
{% elif value.hostname is not exist key2 %}
ping not found
{% endif %}
{% endfor %}
{% endfor %}

所以基本上,如果主机名值在其中一个 ping 键中,那么它就是成功的。如果没有,则失败。如果主机名存在或不存在怎么说?

你实际上不需要那个嵌套循环,你可以简单地断言 hostname 值是 ping_to 字典中的一个键:

{% for interface_name, interface_value in peers.items() %}
  {%- if ping_to[interface_value.hostname] is defined -%}
    ping is success
  {%- else -%}
    ping is not found
  {%- endif %}
{% endfor %}

另一种更简单的方法是使用 default 过滤器,以便在确实未定义键时获得替代输出。

{% for interface_name, interface_value in peers.items() -%}
  ping is {{ ping_to[interface_value.hostname] | default('not found') }}
{% endfor %}

这两个片段都会给出:

ping is success
ping is success
ping is not found