Ansible Tips and Tricks ( Part 2 )

Davinder Pal
3 min readSep 3, 2020
Courtesy: revelwood.com

Trick 2: Ansible Loop Inside another Loop

If you are Ansible User then you might already know about Nested Loops.

Ref: docs.ansible.com/playbooks_loops.html

Honestly, saying when it was released, I was very surprised that what will be the use case for it. Over Time, I found a couple of use cases for it and Today, I will explain one really cool use case of it which I have used in my project.

Project: Automation of Apache Kafka

If you know a little bit about Apache Kafka then you will understand that you have multiple configurations files that need to be created/updated for Apache Kafka to work.

Our Example:

Try 1:
Make it Simple
, as Ansible Motto suggests. All Tasks in One Big Task file.

Task 1: copy template x
Task 2: copy template y
Task 3: copy template z
.....

Problems with Try 1

1. One Task file will become enormously long.

2. There is no way, I can run Task 2 only, As Ansible is suppose to be idempotent. We can whole task file and It will work but it will take more time.

Try 2:

Task 1: copy template x ( task1.yml )
Task 2: copy template y ( task2.yml )
Task 3: copy template z ( task3.yml )
.....

Problems with Try 2

1. Number of files will increase and at some point it becomes very hard to manage too many files.

2. Code Length will increase and it will look like someone just copy pasted multiple times and just wanted to finish his job.

3. It does solve problem from Try 1 which is if I need to run Task 2 only, I can run it with “include_role” in conjunction with “tasks_from” parameter.

Try 3:

I am gonna make use of the Inner & outer Loop Feature of Ansible.

Main File:Run Dynamic Task: copy template
parameter list:
template x
template y
.....
Dynamic Task:
Actual Copy of Template

here is an actual working example

Dynamic Task Content ( Inner.yml )

---
- name: Creating kafka configurations | {{ kafkaConfigFile }}
template:
src: "{{ kafkaConfigFile }}"
dest: "{{ kafkaInstallDir }}/kafka_{{ kafkaScalaVersion }}-{{ kafkaVersion }}/config/{{ kafkaConfigFile }}"
register: configStatus

how to dynamically use ( inner.yml)?

Example 1 ( update two or more files/bulk task )

- name: Creating kafka configurations
include_role:
name: configure
tasks_from: dynamicConfigs.yml
vars:
- kafkaConfigFile: "{{ item }}"
loop:
- kafka-broker.properties
- log4j.properties

Example 2: ( run only 1 task/file)

- hosts: clusterNodes:clusterAddNodes
gather_facts: true
serial: 1
tasks:
- include_role:
name: configure
tasks_from: dynamicConfigs
vars:
- kafkaConfigFile: kafka-broker.properties

Why Try 3 is better?

1. less initial code.

2. easy to extend.

3. can run individual tasks at ease.

Hopefully, now you understand the use of it and how it makes ansible playbooks simpler, which is the motto of Ansible. “ Make it Simple”

--

--