我有這樣的 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 鍵中,那么它就是成功的。如果沒有,那么失敗。如果主機名存在或不存在該怎么說?
uj5u.com熱心網友回復:
您實際上不需要該嵌套回圈,您可以簡單地斷言該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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460411.html
上一篇:條件被忽略?
下一篇:使用遞回,我如何讓我的代碼重復?
