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

cor*_*ght 4 python jinja2 salt-stack

我的 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 循环中内嵌应用过滤器。

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

Wah*_*eed 5

好吧,我认为在这种情况下,yaml 文件的结构越好,解决问题的选项就越多。

我建议进行以下重组:

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

然后你可以用不同的方式进行迭代,这可能是一种方式:
{{ prometheus.services | selectattr('enabled', True) | map(attribute='name') | list }}

我希望这有帮助!