Ansible - Create nested variables using the vars plugin
by
Jeremy Canfield |
Updated: September 19 2022
| Ansible articles
Let's say you want to create nested variables, where the "bar" variable is a child of the "foo" variable.
---
- hosts: localhost
vars:
main:
foo: "hello"
tasks:
- name: output the main[foo] nested variable
debug:
var: main[foo]
- name: output the main['foo'] nested variable
debug:
var: main['foo']
---
Running this playbook should return the following. This shows that the nested variable must be wrapped in single quotes to return the value of the nested variable.
TASK [output the main[foo] nested variable]
ok: [localhost] => {
"main[foo]": "VARIABLE IS NOT DEFINED!"
}
TASK [output the main['foo'] nested variable]
ok: [localhost] => {
"main['foo']": "hello"
}
Let's consider a slightly different situation, where one of the nested variables is localhost. In this scenario, instead of using main['localhost']['foo'] you could use main[inventory_hostname]['foo'].
---
- hosts: localhost
vars:
main:
localhost:
foo: "hello"
tasks:
- name: output the value of the foo nested variable
debug:
var: main[inventory_hostname]['foo']
---
If inventory_hostname resolves to localhost, then the following output should be returned.
TASK [output the value of the foo nested variable]
ok: [localhost] => {
"main[inventory_hostname]['foo']": "hello"
}
Did you find this article helpful?
If so, consider buying me a coffee over at