小编cor*_*ght的帖子

使用 Jinja 按嵌套字典值进行过滤

我的 SaltStack Pillar 中有以下 YAML:

prometheus:
  services:
    cassandra:
      enabled: False
    cockroachdb:
      enabled: True
    haproxy:
      enabled: True
    swift:
      enabled: False
Run Code Online (Sandbox Code Playgroud)

我希望能够循环访问已启用的服务列表。

{% for enabled_service_name in prometheus.services | selectattr('enabled') %}
{{ enabled_service_name }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为我尝试过滤的属性位于服务名称下方的嵌套字典中:

prometheus:
  services:
    cassandra:
      enabled: False
    cockroachdb:
      enabled: True
    haproxy:
      enabled: True
    swift:
      enabled: False
Run Code Online (Sandbox Code Playgroud)

我显然可以通过在循环内应用条件测试来实现我想要的:

{% for name, properties in prometheus.services | dictsort %}
{% if properties.enabled %}
configuration for {{ name }}
{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

然而,我会经常循环这个列表,并且更喜欢让 Jinja 在 for 循环中内嵌应用过滤器。

有没有办法按嵌套字典中项目的值进行过滤?

python jinja2 salt-stack

4
推荐指数
1
解决办法
2843
查看次数

标签 统计

jinja2 ×1

python ×1

salt-stack ×1