Ansible Tips and Tricks ( Part 1 )

Trick 1: Variable Inside Another Variable

"{{ 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"
}

--

--

--

Senior Software Engineer III ( R&D )

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Which Is The Best Digital Tool To Get Tungsten Prices Per Troy Ounce?

Code is WORM: Act Accordingly

Uptime Monitoring in Data Platforms

Power of interfaces in Software Development

Dynamics 365 Workflow Activity — Calculate Rollup Field(CalculateRollupFieldRequest)

Using Rust and Nom to create an open source programming language for chatbots

EOQ stands for ____?

SLAE 0x5: Part II — Analyzing MSFvenom ‘linux/x86/meterpreter/reverse_tcp’ shellcode

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

Senior Software Engineer III ( R&D )

More from Medium

How to find files in Bash?

Docker Journey — Part 2

How to backup and clone your Jenkins Instance

Docker Installation & Basic Commands