Ansible Tips and Tricks ( Part 2 )


Trick 2: Ansible Loop Inside another Loop

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


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.

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:

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.

here is an actual working example

Dynamic Task Content ( Inner.yml )

how to dynamically use ( inner.yml)?

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

Example 2: ( run only 1 task/file)

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”

Senior Software Engineer III ( R&D )