Bookmark this page

Guided Exercise: Looping Over a Filtered List

In this exercise, you will construct loops and conditionals in Ansible Playbooks.

Outcomes

You should be able to use a filter to loop over items selected from a list.

Open a terminal window on the workstation VM and change to your ~/proj/ directory.

Procedure 3.3. Instructions

  1. Add an ipv4_addresses list variable to your vars/myvars.yml file:

    dest: 172.25.250.9
    ipv4_addresses:
      - 172.25.250.8
      - 172.25.250.9
      - 172.25.250.51
      - 172.25.250.61
      - 172.25.250.151
      - 172.25.250.161
      - 172.25.250.195
      - 8.8.8.8
  2. Create a playbook named iosping7.yml that uses this file for data, but disregards addresses not associated with the 172.25.250.0/24 subnet. You saw how to use vars_files to separate data from code. That makes it possible to maintain the data independently. The available data, however, might be broader in scope than the present task requires. A list of IP addresses, for instance, might contain many addresses that are of no interest with respect to the task at hand. Your playbook should contain the following:

    ---
    - name: A reachability test
      hosts: cs01
      vars_files:
      - vars/myvars.yml
    
      tasks:
    
      - name: "test reachability from {{ inventory_hostname }} to {{ dest }}"
        ios_ping:
          dest: "{{ item }}"
        loop: "{{ ipv4_addresses | select('match', '^172\\.25\\.250\\..*') | list }}"
        when: ansible_network_os == 'ios'
  3. Verify the syntax and run the play:

    [student@workstation proj]$ ansible-playbook iosping7.yml
    SSH password: student
    
    PLAY [A reachability test] *****************************************************
    
    TASK [Test reachability from cs01 to 172.25.250.9] *****************************
    ok: [cs01] => (item=172.25.250.8)
    ok: [cs01] => (item=172.25.250.9)
    ok: [cs01] => (item=172.25.250.51)
    ok: [cs01] => (item=172.25.250.61)
    ok: [cs01] => (item=172.25.250.151)
    ok: [cs01] => (item=172.25.250.161)
    ok: [cs01] => (item=172.25.250.195)
    
    PLAY RECAP *********************************************************************
    cs01                      : ok=1   changed=0   unreachable=0   failed=0

This concludes the guided exercise.

Revision: do457-2.5-4693601