Ansible Tips and Tricks ( Part 1 )

A little bit about myself, I am DevOps Engineer and I have around 4 years of experience in Ansible since version 2.2 / 2016. I have done 50+ projects in Ansible.

I will be sharing tricks that I learnt over time while using Ansible.

Trick 1: Variable Inside Another Variable

So let’s suppose you one variable or result which is being generated by some task. Now you want to use that Result / Variable Inside another variable to generate some value or another result.

"{{ variable_A {{ variable_B }} }}"

Above Syntax won’t work.

Let’s take an example and see.

Try 1:

I will add curly brackets inside another curly bracket like a lazy developer.

- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1[{{ v2 }}] }}"

Try 2:

I keep curly brackets inside another curly bracket but will add single quotes to inside brackets to make it separate.

- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1['{{ v2 }}'] }}"

Try 3:

Ansible has a special syntax for it which is to use square brackets and without any curly brackets on the inside variable, Ansible Engine will automatically populate inside variable first then outside variable.

- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1[v2] }}"

It can be enhanced a bit more to make it simple to understand and faster execution.

Try 4:

Add Type of inside variable like Int / String / etc .

- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1[v2 | int ] }}"

Have a fun day! and Keep Learning.

Senior Software Engineer III ( R&D )