首页 > 解决方案 > 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 多次发布。

标签: ansible

解决方案


问:条件:状态不是‘关闭’的商店包含商品‘苹果’

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

解释

  1. 拒绝列入黑名单的状态
    - debug:
        msg: "{{ _not_closed }}"
      vars:
        _not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"

  msg:
  - items:
    - apple
    - banana
    name: store2
    state: open
  1. 映射和展平项目
    - debug:
        msg: "{{ _not_closed|map(attribute='items')|flatten }}"
      vars:
        _not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"

  msg:
  - apple
  - banana
  1. 测试一个苹果是否在项目中
    - debug:
        msg: "{{ 'apple' in _not_closed|map(attribute='items')|flatten }}"
      vars:
        _not_closed: "{{ stores|rejectattr('state', 'in', black_list)|list }}"

  msg: true

推荐阅读