Search code examples
automationansiblecisco-ios

Remove first line in 'stdout_lines'


I'm just a beginner and write some small playbook.

For now I get some little error.

- name: Facts
  ios_command:
    commands: show interface status
  register: ios_comm_result

In this playbook, for beginner I get the list of interfaces and then in next task I get list with first position including column name.

- name: get a list of ports to modify
  set_fact:
    newlist: "{{ (newlist | default([])) + [item.split()[0]] }}"
  with_items: "{{ ios_comm_result.stdout_lines }}"

Output:

'Port'
'fa0/1'
'gi0/2'
....
 etc

How can I delete first line? Or where can I read about this?


Solution

  • Based on your requirement and the given comments about Accessing list elements with Slice notation ([1:]) and Jinja Filters (| reject()) I've setup an short test

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        STDOUT_LINES: ['Port', 'fa0/1', 'gi0/2', 'etc/3']
    
      tasks:
    
      # Slice notation
    
      - name: Show 'stdout_lines' from the 2nd line to the end
        debug:
          msg: "{{ item }}"
        loop: "{{ STDOUT_LINES[1:] }}"
    
      # Jinja2 filter
    
      - name: Show 'stdout_lines' and drop any lines which match
        debug:
          msg: "{{ item }}"
        loop: "{{ STDOUT_LINES | reject('match', '^Port') | list }}"
    
      # Conditionals
    
      - name: Show 'stdout_lines' but not the first one
        debug:
          msg: "{{ item }}"
        when: ansible_loop.index != 1
        loop: "{{ STDOUT_LINES }}"
        loop_control:
          extended: true
          label: "{{ ansible_loop.index0 }}"
    

    with some value added about Extended loop variables and using conditionals in loops.

    All three options show the expected result.