簡體   English   中英

使用 jinja2 展平 ansible 結果

[英]flatten ansible result using jinja2

我正在使用 ansible 獲取相同結構的元素列表,它看起來有點像以下內容:

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

我需要遍歷所有元素的 c 的所有子元素,所以我想要的是元素列表:c1、c2、c3、c4、c5、c6 ......

通常我會使用嵌套循環,但由於 ansible 使用的是 jinja2s 過濾器,我不知道如何實現這一點。 我對這種數據轉換完全陌生。


為了給出一些上下文,實際的代碼是:

- 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"

是的,我知道我可以傳遞一個要查找的路徑列表,但這不是我想要 go 的方式,而是我想了解如何在這種情況下使用過濾器。

例如,

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

給出列表

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

用於測試的完整劇本示例

- 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 }}"

給出(刪節)

 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