Ansible:如何基于count>0过滤set_fact提取的路径列表
问题描述
我拿到了如下Ansible任务的执行结果:
ok: [localhost] => { "register_xpathwithbranches": { "changed": false, "msg": "All items completed", "results": [ { "actions": { "namespaces": {}, "state": "present", "xpath": "//branches//name" }, "ansible_loop_var": "validpath", "changed": false, "count": 1, "failed": false, "invocation": { "module_args": { "path": "mypath/config.xml", } }, "msg": "found 1 nodes", "validpath": "Anotherpath" }, { "actions": { "namespaces": {}, "state": "present", [...]
其中results是包含大量条目的数组,每个条目包含invocation->module_args->path字段,以及取值为0或1的count字段。我需要仅提取count>0的所有路径。
目前使用的set_fact任务能提取所有路径,但无法实现count>0的过滤:
- name: Transform the var as a list set_fact: xpathwithbranches_list: "{{ register_xpathwithbranches.results | map(attribute='invocation.module_args.path') |list }}"
已经运行228次Jenkins作业仍未解决,不确定是否该继续用set_fact,还是改用register或循环,求解决方案。
解决方案
直接在现有set_fact任务中添加selectattr过滤器即可实现过滤,无需更换其他方法。修改后的任务如下:
- name: Transform the var as a list (filter count>0) set_fact: xpathwithbranches_list: "{{ register_xpathwithbranches.results | selectattr('count', '>', 0) | map(attribute='invocation.module_args.path') | list }}"
逻辑说明:
selectattr('count', '>', 0):先从results数组中筛选出count值大于0的条目map(attribute='invocation.module_args.path'):提取筛选后条目中的路径字段list:将最终结果转换为列表格式
若需要验证过滤后的结果,可添加调试任务:
- name: Debug filtered paths debug: var: xpathwithbranches_list
内容的提问来源于stack exchange,提问作者IlliciteS
相关产品推荐
相关产品推荐

