您如何使用整数列表迭代列表?

露丝边缘

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

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

返回

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

然后我想遍历列表并获取真/假值

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

β.εηοιτ.βε

只需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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章