ansible

Iterating over a list for a set number of times in Ansible


I am new to Ansible, trying to achieve the following: Store the output in an array, and iterate over the array " COUNT" times, where count is the total number of elements minus one in the array/list.

Below is my example playbook.

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


Solution

  • Q: "Iterate over the array COUNT times, where COUNT is the total number of elements in the array minus one."

    A: It's possible to use nested. The playbook below

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

    gives

    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"