ansible - Ansible 过滤器根据子列表值了解项目是否存在
问题描述
这似乎是一项非常简单的任务,但我找不到关于 json_query、map 等内容的系统文档或教程。只有我不适合它们的示例。如果你知道,请推荐一个。
有一个结构如下的列表。商店、商品和商品名称的数量可能会有所不同。
stores:
- name: store1
state: closed
items:
- apple
- banana
- name: store2
state: open
items:
- apple
- banana
- name: store3
state: closeout
items:
- apple
- orange
这是我的任务:
- debug:
msg: "Apple is on the market"
when: ***< need help to get a condition here >***
上面的条件需要 商店包含状态不是“关闭”的商店并且项目包含“苹果”
想要使用when而不是任何循环来避免 msg 多次发布。
解决方案
问:“条件:状态不是‘关闭’的商店包含商品‘苹果’ ”
A:使用测试并拒绝列入黑名单的状态。创建要拒绝的状态列表,例如
black_list:
- closed
- closeout
然后下面的任务就完成了
- debug:
msg: "Apple is on the market"
vars:
_not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"
when: "'apple' in _not_closed|map(attribute='items')|flatten"
给
msg: Apple is on the market
解释
- 拒绝列入黑名单的状态
- debug:
msg: "{{ _not_closed }}"
vars:
_not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"
给
msg:
- items:
- apple
- banana
name: store2
state: open
- 映射和展平项目
- debug:
msg: "{{ _not_closed|map(attribute='items')|flatten }}"
vars:
_not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"
给
msg:
- apple
- banana
- 测试一个苹果是否在项目中
- debug:
msg: "{{ 'apple' in _not_closed|map(attribute='items')|flatten }}"
vars:
_not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"
给
msg: true
推荐阅读
- ansible - Ansible JSON解析空字符串
- python - 多处理池有一个 map() 函数 - 是否有类似的方法可以将多处理应用于 reduce()?
- javascript - JS循环添加事件侦听器在第二个元素的一个条件下不起作用
- flutter - Flutter:资产音频播放器
- angular - Angular 9 IVY 延迟加载组件与 AngularFireMessagingModule R3InjectorError(AppBrowserModule)[InjectionToken angularfire2.app.options
- git - 如果我必须 git clone 整个项目并使用“vsce 包”生成它,如何生成与 vscode 扩展中的相同的 VSIX 文件?
- firebase - Firestore 查询正在返回数据,但 Futurebuilder 说它不能为空
- node.js - 如何让 ESLint 识别聚合导出命名空间?
- node.js - Karma 测试运行器不运行 mocha 测试
- javascript - 递归通过无限循环运行