基于条件的Ansible合并列表

问题描述

我有两个列表:

list1:
  - file: f1
    perm: '777'
  - file: f2
    perm: '677'
  - file: f3
    perm: '755'
  - file: f4
    perm: '700'
list2:
  - file: f4
    t_perm: '755'
  - file: f3
    t_perm: '677'
  - file: f10
    t_perm: '777'

我必须将它们合并到新列表中,如下所示:

list3:
  - file: f1
    perm: '777'
  - file: f2
    perm: '677'
  - file: f3
    perm: '755'
    t_perm: '677'
  - file: f4
    perm: '700'
    t_perm: '755'

正常合并是通过

   - set_fact:
        list3: "{{ (list1 + list2)|
                   groupby('file')|
                   map('last')|
                   map('combine')|
                   list }}"

但是我还有一个条件。如果文件存在于list1中而不存在于list2中,则合并。如果文件存在于list2中而不存在于list1中,则不要合并,请忽略该文件。

解决方法

要满足条件,我们需要从list2中删除不在list1中的项目

  1. “在list1中”和“不在list2中” =>合并
  2. “在list2中”和“不在list1中” =>不要合并

例如,intersect的文件列表并获得my_keys。使用列表1和列表2中的文件创建my_list,并将其用于已测试的任务set_fact

    - set_fact:
        list3: "{{ (list1 + my_list)|
                   groupby('file')|
                   map('last')|
                   map('combine')|
                   list }}"
      vars:
        my_keys: "{{ list2|map(attribute='file')|
                     intersect(list1|map(attribute='file'))|
                     list }}"
        my_list: "{{ list2|selectattr('file','in',my_keys)|
                     list }}"
    - debug:
        var: list3

给予

  list3:
  - file: f1
    perm: '777'
  - file: f2
    perm: '677'
  - file: f3
    perm: '755'
    t_perm: '677'
  - file: f4
    perm: '700'
    t_perm: '755'

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...