In this exercise, you will construct loops and conditionals in Ansible Playbooks.
Outcomes
You should be able to:
Use an Ansible loop in conjunction with conditionals.
Use the when statement to control the flow of task execution in plays.
Open a terminal window on the workstation VM and change to your ~/proj/ directory.
Procedure 3.2. Instructions
Create a file named iosping6.yml with a single task that loops over a variable named interesting_destinations, consisting of a list of IPv4 addresses.
The resulting playbook should appear similar to the following:
---
- name: A reachability test
hosts: cs01
vars:
interesting_destinations:
- 172.25.250.8
- 172.25.250.9
tasks:
- name: "test reachability from {{ inventory_hostname }}"
ios_ping:
dest: "{{ item }}"
loop: "{{ interesting_destinations }}"Verify the syntax and run the play:
[student@workstation proj]$ansible-playbook --syntax-check iosping6.yml[student@workstation proj]$ansible-playbook iosping6.yml
The required SSH password is student.
The when statement can be used to consolidate plays in multivendor playbooks.
To keep things relatively simple, we look at how this works with a playbook designed to deal with a single target host at a time.
Create a playbook named multi-vendor-syscheck2.yml.
The individual tasks are similar to your multivendor-syscheck.yml playbook.
Modify it so that it contains a single play, and sets the value of hosts based on an extra variable named target.
Conditionally run the tasks based on the value of the ansible_network_os variable.
[student@workstation proj]$cat multi-vendor-syscheck2.yml- name: back up config and record device health indicators hosts: network tasks: - name: backup vyos config vyos_config: backup: yes when: ansible_network_os == "vyos" - name: look at vyos device health indicators vyos_command: commands: - sh host name - sh system uptime - sh host domain - sh host date - sh host os - sh sys mem register: vyos_result when: ansible_network_os == "vyos" - name: backup ios config ios_config: backup: yes when: ansible_network_os == "ios" - name: look at ios device health indicators ios_command: commands: - sh ver | include uptime - sh ip domain - sh clock - sh ip name-server - sh proc mem platform | include System memory register: ios_result when: ansible_network_os == "ios" - name: show results debug: msg: "{{ item }}" loop: "{{ (vyos_result | combine(ios_result)).stdout_lines }}"
Run the new playbook, using the limit option (-l ) as shown here:
SUBSET
[student@workstation proj]$ansible-playbook -l cs01 multi-vendor-syscheck2.yml
Or like this:
[student@workstation proj]$ansible-playbook -l vyos multi-vendor-syscheck2.yml
Since you have removed the password extra-vars from this version, you must provide the appropriate password when running the playbook.
Use the vyos password for the spine and leaf VyOS devices.
Use the student password for the IOS device, cs01.
This concludes the guided exercise.