Ansible Tips and Tricks ( Part 1 )

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 }} }}"
- 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 }}] }}"}
- 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"}
- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1[v2] }}"
TASK [debug] ********************************************************************
ok: [localhost] => {
"msg": "3"
}
- hosts: localhost
vars:
v1: [1,2,3,4]
v2: 2
tasks:
- debug: msg="{{ v1[v2 | int ] }}"
TASK [debug] ********************************************************************
ok: [localhost] => {
"msg": "3"
}

--

--

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
Davinder Pal

Davinder Pal

Principal Software Architect I ( R&D DevOps )