繁体   English   中英

Jinja2/Ansible 中的嵌套变量

[英]Nested Variables in Jinja2/Ansible

我很难理解如何在 Jinja2/Ansible 中使用嵌套变量

我在 yaml 文件中有以下变量

dual_homed_workloads:
  switch1:
    - tag: 200
      description: DB-Servers
      ports:
      lags: [1,2,4]
    - tag: 201
      description: Storage
      ports:
      lags: [1,2,4]
    - tag: 202
      description: iLo
      ports:
      lags: [1,3,4]
  switch2:
    - tag: 200
      description: DB-Servers
      ports:
      lags: [3,4]
    - tag: 211
      description: voice
      ports:
      lags: [1,]
    - tag: 2000
      description: egree
      ports:
      lags: [2,3]

我想搜索与inventory_hostname匹配的交换机名称,然后获取 VLAN 的标签

{% for vlan, switch in dual_homed_workloads %}
{% if switch == inventory_hostname %}
VLAN {{ vlan.tag }}
  name {{ vlan.descrption }}
{% endif %}
{% endfor %}

如果我要为开关 1 运行它,我想要一个 output,如下所示

vlan 200
 name DB-Servers
vlan 201
 name Storage
vlan 202
 name iLo

LAGs 也是一个列表,有没有办法在该列表中搜索值,例如"1"

谢谢

以下将为等于当前inventory_hostname的开关键循环其他所有 vlan,过滤掉lags列表中不包含1的所有 vlan:

{% for vlan in dual_homed_workloads[inventory_hostname] if 1 in vlan.lags %}
VLAN {{ vlan.tag }}
  name {{ vlan.description }}
{% endfor %}

这里有 2 个变体,因为我不确切知道你打算在lags键中寻找什么。

保留lags 1 或滞后 2 中的 vlan:

{% for vlan in dual_homed_workloads[inventory_hostname] if vlan.lags | intersect([1,2]) | length > 0 %}
VLAN {{ vlan.tag }}
  name {{ vlan.description }}
{% endfor %}

只保留滞后 1 和滞后 2 的 vlan:

{% set keep_lags = [1,2] %}
{% for vlan in dual_homed_workloads[inventory_hostname] if vlan.lags | intersect(keep_lags) | length == keep_lags | length %}
VLAN {{ vlan.tag }}
  name {{ vlan.description }}
{% endfor %}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM