Loops in Ansible Playbook
To demonstrate the 'loop' in Ansible, let's take tasks from a playbook I used in another training to configure a Kubernetes cluster.
---
- name : Install the required packages, set the Selinux to permissive , disable the swap etc
hosts: all
become : True
tasks :
- name: Ensure SELinux is set to permissive mode in the configuration file
lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=permissive
- name: Put SELinux in permissive mode.
ansible.posix.selinux:
policy: targeted
state: permissive
- name: Configure required modules
shell : modprobe overlay ; modprobe br_netfilterLet's break down the playbook and then enhance the last task to utilize an Ansible loop.
Setting SELinux to Permissive Mode:
The first two tasks focus on SELinux configuration.
In the
lineinfiletask, we ensure that theSELINUXline in the/etc/selinux/configfile is set topermissive.The
ansible.posix.selinuxtask puts SELinux in permissive mode for the targeted policy.
Configuring Required Modules:
The third task executes a shell command to load two kernel modules:
overlayandbr_netfilter.These modules are essential for containerization and network filtering.
Enhancing the Last Task with an Ansible Loop:
Instead of using a shell command directly, let's modify the last task to use an Ansible loop.
We'll use the
loopkeyword to iterate over a list of module names and load them.Here's the updated task:
In this new task:
The
shellmodule runs themodprobecommand for each item in the loop.The
itemvariable represents the current module name (e.g.,overlay,br_netfilter).
Now your playbook will dynamically load the specified modules using the Ansible loop!
One other section of the playbook that can be optimized with 'loop' is given below.
We'll consolidate this into a single task that iterates over the required parameters.
In this updated task:
The
lineinfilemodule will add each parameter line to the specified file.The
loopiterates over the list of parameters, ensuring cleaner and more concise code.
Here is another instance of 'loop' in the same playbook, which should be self-explanatory. Like this, the playbooks can be simplified and enhanced with appropriate loops.
Reference
Last updated