I have a YAML data like this :
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
with jinja2,Ii want to define something like this:
{% 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 %}
So basically if the hostname value is in one of the ping keys, then it is a success. If not, then fail. how to say it if the hostname exists or does not exist?
CodePudding user response:
You actually do not need that nested loop, you could simply assert that the hostname
value is a key in the ping_to
dictionnary:
{% 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 %}
Another, simpler way, would be to use the default
filter, to have an alternative output when the key is indeed not defined.
{% for interface_name, interface_value in peers.items() -%}
ping is {{ ping_to[interface_value.hostname] | default('not found') }}
{% endfor %}
Both those snippets would give:
ping is success
ping is success
ping is not found