简体   繁体   English

如何根据其他字典过滤ansible中的字典

[英]How filter a dictionary in ansible based on other dictionary

How to filter dictionary based on other dictionary by matching certain key/value pair.如何通过匹配某个键/值对来根据其他字典过滤字典。 It works if dictionary_1 and dictionary_2 has same key/value pairs by using |如果dictionary_1 和dictionary_2 通过使用| 具有相同的键/值对,它就可以工作。 difference(), but not working if number of key/value pairs are different.差异(),但如果键/值对的数量不同,则不起作用。

- name: difference of two lists
  debug:
    var: my_dict_1 | difference(my_dict_2)
  register: output

My data sets are below我的数据集如下

my_dict_1:
  - build: 0.0.15
    version: 15.1.4.1
    name: HD1.1
  - build: 0.0.10
    version: 15.1.2.1
    name: HD2.1
  - build: 0.0.20
    version: 15.1.3.1
    name: HD3.1
  - build: 0.0.30
    version: 16.1.3.1
    name: HD4.1
my_dict_2:
  - build: 0.0.15
    version: 15.1.4.1
  - build: 0.0.10
    version: 15.1.2.1

I am looking for output as below after comparing/removing my_dict_2 out of my_dict_1:在比较/从 my_dict_1 中删除 my_dict_2 之后,我正在寻找如下输出:

output:
  - build: 0.0.20
    version: 15.1.3.1
    name: HD3.1
  - build: 0.0.30
    version: 16.1.3.1
    name: HD4.1

Create a list of indexes by the combination of the attributes build and version通过属性buildversion的组合创建索引列表

remove: "{{ my_dict_2|json_query('[].[build,version]')|
                      map('join', '_')|
                      list }}"
output: []

gives

remove:
  - 0.0.15_15.1.4.1
  - 0.0.10_15.1.2.1

Then iterate the list and select items然后迭代列表并选择项目

    - set_fact:
        output: "{{ output + [item] }}"
      loop: "{{ my_dict_1 }}"
      when: idx not in remove
      vars:
        idx: "{{ item.build }}_{{ item.version }}"

gives

output:
  - build: 0.0.20
    name: HD3.1
    version: 15.1.3.1
  - build: 0.0.30
    name: HD4.1
    version: 16.1.3.1

Example of a complete playbook完整剧本示例

- hosts: localhost vars: my_dict_1: - build: 0.0.15 version: 15.1.4.1 name: HD1.1 - build: 0.0.10 version: 15.1.2.1 name: HD2.1 - build: 0.0.20 version: 15.1.3.1 name: HD3.1 - build: 0.0.30 version: 16.1.3.1 name: HD4.1 my_dict_2: - build: 0.0.15 version: 15.1.4.1 - build: 0.0.10 version: 15.1.2.1 remove: "{{ my_dict_2|json_query('[].[build,version]')| map('join', '_')| list }}" output: [] tasks: - set_fact: output: "{{ output + [item] }}" loop: "{{ my_dict_1 }}" when: idx not in remove vars: idx: "{{ item.build }}_{{ item.version }}" - debug: var: output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM