我正在尝试将 dict 列表传递给 Ansible 角色,该角色需要按照下面定义的变量。
var1:
- path: /A/1
state: directory
- path: /B/1
state: directory
...
假设我有一个根目录列表:
root_dirs:
- A
- B
- C
...
以及常见子目录列表:
sub_dirs:
- 1
- 2
- 3
- 4
- 5
...
是否有一种简单的方法可以构建上述
var1
列表,而无需输入所有路径组合?
我知道如何组合路径(
root_dirs | product(sub_dirs) | map("join", "\")
),但不知道如何将其变成var1
。尝试在 AWX 模板中执行此操作并避免创建带有循环的剧本。这可行吗?
dict_kv
过滤器可以帮助您将单个值转换为字典。从那里开始,您还可以
map
combine
过滤器来添加所需的 state
。
给定任务:
# 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
您会得到预期的词典列表:
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