你如何迭代一个包含整数列表的列表?

How do you iterate over a list with a list of integers?

我想要一个布尔值列表,对应文件是否存在。

- name: test
  debug:
    msg: "{{ result.results.0.stat.exists }}"

returns

TASK [test] **************************************************************
ok: [localhost] => {
    "msg": true
}

所以我需要一个从零到文件数的数字列表

- name: set fact test
  set_fact:
    outcome: "{{ result.results }}"
    numOfElems: "{{ repoFiles|length }}"
    numList: []
    boolList: []

- name: obtain index  list
  set_fact:
    numList: "{{ numList + item|list }}"
  with_sequence: start=0 end={{ numOfElems }}

然后我想遍历列表并获取 true/false 值

- name: obtain boolean list
  debug:
    msg: "{{ outcome.{{ item }}.stat.exists }}"
  with_items: "{{ numList }}"

- name: obtain boolean list
  set_fact:
    boolList: "{{ outcome.{{ item }}.stat.exists }}"
  with_items: "{{ numList }}"

产生的错误:

TASK [output exists] ******************************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected name or number. String: {{ outcome.{{ item }}.stat.exists }}"}

不知道为什么我不能将数字放入模板字符串中。

每个接受的答案我得到:

ok: [localhost] => {
    "result.results | map(attribute='stat.exists') | list": [
        true,
        false,
        false,
        false,
        true,
        false,
        false,
        false,
        false,
        false,
        true,
        true,
        true
    ]
}

遍历此输出得到字符:"r","e","s","u","l","t"

尝试这些任务:

- name: obtain boolean list
  debug:
    msg: "{{ outcome[item].stat.exists }}"
  with_items: "{{ numList }}"

- name: obtain boolean list
  set_fact:
    boolList: "{{ boolList | d([]) + [ outcome[item].stat.exists ] }}"
  with_items: "{{ numList }}"

- name: display boolList
  debug:
    msg: "{{ boolList }}" 

只需map您要查找的属性:

- debug:
    var: result.results | map(attribute='stat.exists')

鉴于剧本:

- hosts: localhost
  gather_facts: no
  vars:
    files:
        - /tmp/a
        - /tmp/b
        - /tmp/do-not-exists

  tasks:
    - stat:
        path: "{{ item }}"
      register: result
      loop: "{{ files }}"

    - debug:
        var: result.results | map(attribute='stat.exists')

这产生:

TASK [stat] ***************************************************************
ok: [localhost] => (item=/tmp/a)
ok: [localhost] => (item=/tmp/b)
ok: [localhost] => (item=/tmp/do-not-exists)

TASK [debug] **************************************************************
ok: [localhost] => 
  result.results | map(attribute='stat.exists'):
  - true
  - true
  - false