ansible - 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
.
解决方案
有几种方法可以做到这一点(使用 ansible 2.7。不确定较低版本):
纯过滤方式(使用selectattr
and 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 loop
withwhen
语句:
- set_fact: app_list="{{ (app_list | default([])) + [ item.app ] }}"
loop: "{{ data }}"
when: item.app is defined and item.app == true
推荐阅读
- javascript - 如何在窗口中使用 Google 字体。在 React 中打开
- java - 有没有办法将 csv/json 文件从外部加载到 jar 中?
- django - Django 错误,即使我启动一个全新的应用程序并运行它,也会经常遇到相同的服务器错误
- ruby - 当相同的命令在命令行上运行时,如何通过 Ruby shell 命令运行应用程序
- python - 在 Fabric 中,如何从远程路径创建全局列表
- sql - 添加转换函数时的 SQL 语法错误
- html - 数字输入侧箭头选择器上的 Angular 6+ HostListener?
- batch-file - CMD 删除包含来自多个文件夹路径的文件的特定文件夹
- python - 由windows服务启动的应用程序可以连接到互联网吗
- if-statement - 如何在 Google 电子表格中有超过 3 个“如果”参数?