首页 > 解决方案 > 在 Ansible 中迭代列表一定次数

问题描述

我是 ansible 的新手,试图实现以下目标:将输出存储在一个数组中,并迭代数组“COUNT”次,其中 count 是数组/列表中的元素总数减一。

下面是我的示例剧本。

  ---
    - name: GETTING INTERFACES
      connection: network_cli
      cli_command:
        command: show  interfaces terse | match ge-
      register: A

    - name: LISTING CONTENTS of LIST
      debug:
        var: A.stdout_lines


    - name: COUNTING ELEMENTS
      set_fact:
        COUNT: "{{ (A.stdout_lines|length)-1 }}"


    - name: DISPLAY
      debug:
        var: COUNT


    - name: ITERATING OVER LIST 
      debug: var=item
      loop: MUST LOOP OVER THE LIST "COUNT" TIMES How can I achieve this?

Thanks and have a good weekend!!

标签: ansible

解决方案


问:“遍历数组 COUNT 次,其中 COUNT 是数组中元素的总数减一。”

A:可以使用嵌套。下面的剧本

shell> cat pb.yml
- hosts: localhost

  vars:

    A:
      stdout_lines:
        - line1
        - line2
        - line3

  tasks:

    - debug:
        msg: "{{ item.0 }} {{ item.1 }}"
      with_nested:
        - "{{ query('sequence', params) }}"
        - "{{ A.stdout_lines }}"
      vars:
        count: "{{ A.stdout_lines|length - 2 }}"
        params: "{{ 'start=0 end=' ~ count }}"

shell> ansible-playbook pb.yml | grep msg\":
    "msg": "0 line1"
    "msg": "0 line2"
    "msg": "0 line3"
    "msg": "1 line1"
    "msg": "1 line2"
    "msg": "1 line3"

推荐阅读