【问题标题】:Ansible merge lists based on condition基于条件的 Ansible 合并列表
【发布时间】:2020-08-12 13:44:21
【问题描述】:

我有两个列表:

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 中,则不要合并,忽略它。

【问题讨论】:

  • 我已经更新了。

标签: list merge ansible


【解决方案1】:

为了满足条件,我们需要从list2中删除list1中没有的项目

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

例如,intersect 文件列表并获得my_keys。使用 list1 和 list2 中的文件创建 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2019-11-21
    • 2021-01-16
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多