Ansible on IOS – How to Loop Through Subset of Interfaces

ansibleansible-playbook

Running WISL on Windows 10 and Ubuntu with ansible 2.9.9. I am new to Ansible. I execute a show on a Cisco device to yield the interfaces on which a given network protocol runs. I then want to extract the interfaces and execute commands on them. In this case to turn off the protocol. Ideally the show command could change easily. As for many protocols this is the consistent way I would check this state. There may be ways Ansible stores this protocol information. Maybe with facts? I found examples using ios_config at https://docs.ansible.com/ansible/latest/modules/ios_config_module.html but the interfaces are hard coded as shown here with the helper example:

- name: configure ip helpers on multiple interfaces
  ios_config:
    lines:
      - ip helper-address 172.26.1.10
      - ip helper-address 172.26.3.8
    parents: "{{ item }}"
  with_items:
    - interface Ethernet1
    - interface Ethernet2
    - interface GigabitEthernet1

My attempt is as follows which gives me the two interfaces with multicast active. But what next to act on those interfaces in a loop? :

  tasks:
  - name: Gather interfaces running PIM
    ios_command:
      commands:
        - show ip pim interface
    register: pim

  - name: Write PIM interface data to file
    copy:
      content: "{{pim.stdout_lines[0]}}"
      dest: "backups/{{ansible_alias}}-pim-interfaces.txt"


  - name: Glean PIM INTF's
    shell: cat backups/{{ ansible_alias }}-pim-interfaces.txt | tr ' ' '\n' | grep 'GigabitEthernet'
    register: pim

  - debug: msg='{{ pim.stdout_lines }}'


TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [10.239.121.2] => {
    "msg": [
        "GigabitEthernet0/0/0",
        "GigabitEthernet0/0/1.125"
    ]
}

Many thanks for any guidance.

Best Answer

This is where you use a loop (which also since 2.5 has caused all with_ directives to be deprecated, though much of the docs don't yet reflect this).

Modifying the Ansible example gives us:

- name: configure ip helpers on multiple interfaces
  ios_config:
    lines:
      - ip helper-address 172.26.1.10
      - ip helper-address 172.26.3.8
    parents: item
  loop: '{{ ["interface "]|product(pim.stdout_lines)|map("join")|list }}'

To just inspect the output:

- debug:
    var: item
  loop: '{{ ["interface "]|product(pim.stdout_lines)|map("join")|list }}'

This loop was modified from How to prepend every string in a list with a prefix in Ansible.