首页 > 解决方案 > Filter data from list of dicts using condition in Jinja2 filter

问题描述

data:
  - { name: foo, app: foo, isweb: true }
  - { name: bar, app: bar, isweb: true }
  - { name: foobar, app: foobar, isweb: false }
  - { name: baz, app: baz, isweb: false }

Desired result is list as:

{% set  list= [] %}
{% for item in data %}
{% if item.isweb == true %}
{{list.append(item.app)}}
{% endif %}
{% endfor %}

Can this be implemented using filters :

{{ data | map(attribute='app') | list | join(' ') }}

Basically the question is how to implement the above for loop using a single line filter (as above) but only get data which have a value of isweb true.

标签: ansiblejinja2

解决方案


有几种方法可以做到这一点(使用 ansible 2.7。不确定较低版本):

纯过滤方式(使用selectattrand map):

- set_fact: app_list="{{ data | selectattr("isweb", "equalto", true) | map(attribute='app') | list }}"

loop在过滤器中使用带有条件的ansible :

- set_fact: app_list="{{ (app_list | default([])) + ([ item.app ] if (item.isweb == True) else []) }}"
  loop: "{{ data }}"

使用 Ansible loopwithwhen语句:

- set_fact: app_list="{{ (app_list | default([])) + [ item.app ] }}"
  loop: "{{ data }}"
  when: item.app is defined and item.app == true

推荐阅读