Ansible Tips and Tricks ( Part 2 )

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
.....

Try 2:

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

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?

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 )

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store