简体   繁体   English

使用 jinja2 展平 ansible 结果

[英]flatten ansible result using jinja2

I am getting a list of elements of the same structure using ansible, it looks a bit like the following:我正在使用 ansible 获取相同结构的元素列表,它看起来有点像以下内容:

results: [
  {
    "a": "foo",
    "b": "bar",
    "c": [
      {"c1": ...},
      {"c2": ...}
      {"c3": ...}]
  },
  {
    "a": "foo2",
    "b": "bar2",
    "c": [
      {"c4": ...},
      {"c5": ...}
      {"c6": ...}]
  }
]

I would need to iterate over all subelements of c - of all elements, so what I want is a list of the elements: c1, c2, c3, c4, c5, c6...我需要遍历所有元素的 c 的所有子元素,所以我想要的是元素列表:c1、c2、c3、c4、c5、c6 ......

Normally I would use a nested loop, but since ansible is using jinja2s filters, I have no clue on how to accomplish that.通常我会使用嵌套循环,但由于 ansible 使用的是 jinja2s 过滤器,我不知道如何实现这一点。 I am totally new to this kind of data transformation.我对这种数据转换完全陌生。


To give some context, the actual code is:为了给出一些上下文,实际的代码是:

- name: Find log files that are older than 1 day
  find:
    paths: "{{ item }}"
    age: 1d
    recurse: no
  register: oldLogs
  loop:
    - "/var/log"
    - "/home/user/log"

- name: print files
  debug:
    msg: "{{ oldLogs.results | <some filters here> }}\n"

Yes, I know I could pass a list of paths to find instead, but that's not the way I want to go, instead I would like to learn on how to use filters in such a situation.是的,我知道我可以传递一个要查找的路径列表,但这不是我想要 go 的方式,而是我想了解如何在这种情况下使用过滤器。

For example,例如,

results_c: "{{ (results|
                map(attribute='c')|
                flatten|
                combine).keys()|list }}"

gives the list给出列表

results_c: [c1, c2, c3, c4, c5, c6]

Example of a complete playbook for testing用于测试的完整剧本示例

- hosts: localhost vars: results: - a: foo b: bar c: - c1: val_1 - c2: val_2 - c3: val_3 - a: foo2 b: bar2 c: - c4: val_4 - c5: val_5 - c6: val_6 results_c: "{{ (results| map(attribute='c')| flatten| combine).keys()|list }}" tasks: - debug: var: item loop: "{{ results_c }}"

gives (abridged)给出(删节)

 TASK [debug] ********************************************************************************* ok: [localhost] => (item=c1) => ansible_loop_var: item item: c1 ok: [localhost] => (item=c2) => ansible_loop_var: item item: c2 ok: [localhost] => (item=c3) => ansible_loop_var: item item: c3 ok: [localhost] => (item=c4) => ansible_loop_var: item item: c4 ok: [localhost] => (item=c5) => ansible_loop_var: item item: c5 ok: [localhost] => (item=c6) => ansible_loop_var: item item: c6

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

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