如何在Ansible中根据list1的name匹配list2并返回对应条目?
Ansible 根据list1的name字段筛选匹配list2条目
实现期望结果1(完整匹配条目)
通过selectattr过滤器结合map提取list1的name列表,筛选list2中匹配的完整字典条目:
- hosts: localhost vars: list1 : - name: game1 - name: game3 list2: - name: game1 type: application version: 123 notes: type: url name: URLNAME page: https://urlname.com - name: game2 type: application version: 223 notes: type: url name: URLNAME page: https://urlname.com - name: game3 type: application version: 333 notes: type: url name: URLNAME page: https://urlname.com - name: game4 type: application version: 443 notes: type: url name: URLNAME page: https://urlname.com tasks: - name: 生成目标name列表 set_fact: target_names: "{{ list1 | map(attribute='name') | list }}" - name: 筛选list2中匹配的完整条目 set_fact: results: "{{ list2 | selectattr('name', 'in', target_names) | list }}" - name: 输出结果1 debug: var: results
执行后results变量会完全符合你给出的期望结果1,包含匹配条目的所有字段。
实现期望结果2(精简版条目)
在筛选基础上,通过map和extract过滤器提取指定字段,生成精简版结果:
- hosts: localhost vars: list1 : - name: game1 - name: game3 list2: - name: game1 type: application version: 123 notes: type: url name: URLNAME page: https://urlname.com - name: game2 type: application version: 223 notes: type: url name: URLNAME page: https://urlname.com - name: game3 type: application version: 333 notes: type: url name: URLNAME page: https://urlname.com - name: game4 type: application version: 443 notes: type: url name: URLNAME page: https://urlname.com tasks: - name: 生成目标name列表 set_fact: target_names: "{{ list1 | map(attribute='name') | list }}" - name: 筛选并提取指定字段生成精简结果 set_fact: results_slim: > {{ list2 | selectattr('name', 'in', target_names) | map('extract', ['name', 'type', 'version']) | map('zip', ['name', 'type', 'version']) | map('dict') | list }} - name: 输出结果2 debug: var: results_slim
这段代码会把匹配条目只保留name、type、version三个字段,符合期望结果2的要求。
内容的提问来源于stack exchange,提问作者zwerk
相关产品推荐
相关产品推荐

