简体   繁体   English

如何通过ansible / jinja2中属性的存在来过滤列表?

[英]How do I filter a list by existance of an attribute in ansible/jinja2?

G'day everyone. 大家好。

I have two ansible tasks like this, running over the 'workernodes' group in the inventory file: 我有两个类似的任务,在清单文件中的'workernodes'组上运行:

- name: count remote files 
  find:
    paths: "{{ data_path }}"
  register: exported_files

- name: sum up number of remote files
  set_fact: 
    sum_of_exported_files: "{{ groups[ workernodes ] | map('extract', hostvars, 'exported_files') | map(attribute='matched') | sum }}"
  run_once: yes

This works fine as long as all are nodes available. 只要所有节点都可用,就可以正常工作。 But if the find-Task count not run on any of the workernodes i get in error in the sum-up task. 但是,如果find-Task计数未在任何workernode上运行,则总结任务会出错。 There is no exported_files variable on for this node, so the mapping to the attribute fails. 该节点上没有export_files变量,因此到属性的映射失败。

How can i filter for the existance of the exported_files attribute in the extarcted hostvars list? 如何过滤已扩展的hostvars列表中export_files属性的存在?

Please EnlightMe 请EnlightMe

Thanks. 谢谢。

when:添加以下内容when:子句:

when: groups[ workernodes ] | map('extract', hostvars, 'exported_files')|list|first|length > 0"

G'day everyone, 大家好,

finally i found the (really simple) answer by myself: 终于我自己找到了(真的很简单)答案:

sum_of_exported_files: "{{ groups[ workernodes ] | map('extract', hostvars, 'exported_files') | select("defined") | map(attribute='matched') | select("number") | sum }}"

Thanks isabellema for your thought that helped me to think it over. 感谢isabellema的想法,这帮助我进行了深思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM