I'm attempting to pass a list of dictionaries to an Ansible role that expects a variable defined per the below.
var1:
- path: /A/1
state: directory
- path: /B/1
state: directory
Let's say I have a list of root directories:
root_dirs:
- A
- B
And a list of common sub directories:
sub_dirs:
- 1
- 2
- 3
Is there an easy way to construct the above var1
list that doesn't involve typing out all of the path combinations?
I know how to combine the paths (root_dirs | product(sub_dirs) | map("join", "\")
), but I am not sure how to turn that into var1
.
I am trying to do this in an AWX template and want to avoid creating a playbook with loops.
Is this possible?
The dict_kv
filter can help you turn a single value into a dictionary.
You can, off course, map it on a list.
From there on, you can also map
a combine
filter to add the desired state
.
Given the task:
# Mind that the extra empty string item
# is there to prefix the `root_dirs` with a slash
- debug:
msg: >-
{{
['']
| product(root_dirs)
| map('join', '/')
| product(sub_dirs)
| map('join', '/')
| map('community.general.dict_kv', 'path')
| map('combine', {'state': 'directory'})
}}
vars:
root_dirs:
- A
- B
sub_dirs:
- 1
- 2
- 3
You get your expected a list of dictionaries:
ok: [localhost] =>
msg:
- path: /A/1
state: directory
- path: /A/2
state: directory
- path: /A/3
state: directory
- path: /B/1
state: directory
- path: /B/2
state: directory
- path: /B/3
state: directory