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 }}] }}"TASK [debug] ********************************************************************
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: expected token ':', got '}'. String: {{ 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 }}'] }}"TASK [debug] ********************************************************************
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute '{{ v2 }}'\n\nThe error appears to be in 'projects/ansible-tricks/trick1.yml': line 10, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - debug: msg=\"{{ v1['{{ v2 }}'] }}\"\n ^ here\n"}
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] }}"TASK [debug] ********************************************************************
ok: [localhost] => {
"msg": "3"
}
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 ] }}"TASK [debug] ********************************************************************
ok: [localhost] => {
"msg": "3"
}
Have a fun day! and Keep Learning.