[英]How to filter element of list with a list in ansible with a json_query or other
I created an ansible playbook. 我创建了一个可笑的剧本。 And I want a task executed only if a json_query returns element.
我希望仅当json_query返回元素时才执行任务。
The json query have to returned an array searching if in an element from array of array exists in an element of another array. json查询必须返回一个数组,搜索数组中的某个元素是否存在于另一个数组的元素中。
I already tried using json_query (jmespath) with simplified queries I read the jmespath doc and try with the website tutorial. 我已经尝试过将json_query(jmespath)与简化查询一起使用,我阅读了jmespath文档并尝试了网站教程。 Read the ansible documentation and try to find example.
阅读Ansible文档并尝试查找示例。
I think the good solution is to use contains built-in functions and map functions. 我认为一个好的解决方案是使用包含内置函数和map函数。 But example with map and the documentation is not clear for me.
但是对我来说,带有地图和文档的示例尚不清楚。
Example : 范例:
array_of_array_to_check : [
{
hosts : ["host1", "host2"],
name : "name1"
},
{
hosts : [ "host3", "host1"],
name : "name2"
},
{
hosts : ["host4", "host5"],
name : "name3"
}
]
array_parameters: ["host1", "host18"]
Expected : 预期:
result: [
{
hosts: ["host1", "host2"],
name: "name1"
},
{
hosts: ["host3", "host1"],
name: "name2"
}
]
here is a way to do it: 这是一种方法:
---
- hosts: localhost
gather_facts: false
vars:
array_of_array_to_check:
- hosts:
- host1
- host2
name: name1
- hosts:
- host3
- host1
name: name2
- hosts:
- host4
- host5
name: name3
array_parameters:
- host1
- host18
tasks:
- name: parse array and add to results
set_fact:
results_array: "{{ results_array | default([]) + [item] }}"
when: item.hosts | intersect(array_parameters) | length > 0
with_items:
- "{{ array_of_array_to_check }}"
- debug:
var: results_array
basically you parse the array_of_array_to_check
list, and if you find common elements in its elements' hosts
list with the array_parameters
, then you add the whole "item" to the results_array
基本上,您解析
array_of_array_to_check
列表,并且如果您使用array_parameters
在其元素的hosts
列表中找到公用元素,则可以将整个“ item”添加到results_array
intersect
filter gets the "unique list of all items in both" , so if length is more than 0, then there are matches found. intersect
过滤器将获得“所有项目均具有唯一列表”,因此,如果长度大于0,则找到匹配项。
hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.