如何从包含的列表中为with_item创建列表

时间:2018-08-26 13:34:22

标签: ansible jinja2

我有这个列表:

"mylist": [
   { "files": [{"path": "path11"}, {"path": "path12"}] },
   { "files": [{"path": "path21"}, {"path": "path22"}] } 
]

,我需要使用 with_items 来扮演角色,其中项目应该是列表中的 path 元素。

例如:

- debug: msg="{{ item }}"
  with_items: "{{ mylist | some_magic }}"

所需的输出:

TASK [test : debug] **********************************
ok: [host] => (item=path11 ) => {
    "msg": "path11"
}
ok: [host] => (item=path12 ) => {
    "msg": "path12"
}
ok: [host] => (item=path21 ) => {
    "msg": "path21"
}
...

有可能吗?


这是我已经尝试过的:

构造如下:

- debug: msg="{{ item }}"
  with_items: "{% for files in mylist | map(attribute='files') %}{% for file in files %}{{file.path}}{% endfor %}{% endfor %}"

返回的预期值不是列表。

错误的结构看起来像这样:

- debug: msg="{{ item }}"
  with_items: "{{ mylist | map(attribute='files') | map(attribute='path') | list }}"

1 个答案:

答案 0 :(得分:0)

这是旧版with_subelements loop pattern

使用loop关键字(Ansible 2.5及更高版本),您可以进行以下迭代:

- debug:
    msg: "{{ item.1.path }}"
  loop: "{{ mylist | subelements('files') }}"

或与使用JMESPath相同(这显示了如何从整个数据结构中创建列表):

- debug:
    msg: "{{ item }}"
  loop: "{{ mylist | json_query('[].files[].path') }}"