It is so common in the network that you enter the same configuration several times, for example in different interfaces. Instead of writing multiple tasks, you can easily use loop capability of ansible. Ansible Loop is the topic of this video.
access ansible codes of this course in github
this is a video-based training therefore the output of running commands are not show in the text.
Loop can be implemented in Ansible with “loop”, “with_items” and also some other keywords. There are some differences in these methods, however, but I haven’t seen many differences in the network modules. So I’m not talking about details and will implement it here using two methods.
Ansible loop in Ansible Website
In the Ansible playbook that I have already prepared, I want to enable ospf in many interfaces, but instead of writing multiple tasks, I am going to run the ospf command with loop in different interfaces. Once with “loop” keyword and once with “with_items” keyword.
root@debian:~/ansible-project1# cat loop.yaml
---
- hosts: csr
gather_facts: false
connection: local
tasks:
- name: test ios config module
ios_config:
lines:
- no shutdown
- ip ospf 1 area 0
parents: "{{ item }}"
loop:
#with_items:
- interface GigabitEthernet2
- interface GigabitEthernet3