如何在AWX模板中无循环构建Ansible所需的var1字典列表?
在AWX模板中动态构建Ansible字典列表变量
需求
要给Ansible角色传递一个var1变量,格式为字典列表:
var1: - path: /A/1 state: directory - path: /B/1 state: directory # 需覆盖所有根目录+子目录的组合
现有两个基础列表变量:
root_dirs: - A - B sub_dirs: - 1 - 2 - 3
希望无需手动枚举所有路径组合,直接生成var1,且在AWX模板中完成,避免在Playbook里编写循环逻辑。
解决方案
完全可行,直接通过Ansible过滤器链式调用即可生成目标格式,在AWX的Extra Variables模板中按如下方式定义var1:
var1: "{{ root_dirs | product(sub_dirs) | map('join', '/') | map('regex_replace', '^(.*)$', '/\\1') | map('community.general.dict', state='directory') | list }}"
过滤器逻辑拆解
root_dirs | product(sub_dirs):生成根目录与子目录的笛卡尔积,得到类似['A','1'], ['A','2'], ['B','1']的元组列表map('join', '/'):将每个元组拼接为A/1、A/2这类相对路径map('regex_replace', '^(.*)$', '/\\1'):给路径添加开头的斜杠,转换为/A/1、/A/2的绝对路径格式map('community.general.dict', state='directory'):将每个路径字符串转换为{path: "路径值", state: "directory"}的字典结构| list:将最终的迭代器转换为标准列表格式
无community.general集合的替代写法
如果未安装community.general集合,可使用原生过滤器组合实现:
var1: "{{ root_dirs | product(sub_dirs) | map('join', '/') | map('regex_replace', '^(.*)$', '/\\1') | map('zip', ['path']) | map('dict') | map('combine', {'state': 'directory'}) | list }}"
AWX使用说明
直接将上述变量定义粘贴到AWX的Extra Variables模板中即可,AWX会在执行Playbook前自动完成变量计算,无需编写任何循环代码。
内容的提问来源于stack exchange,提问作者Kimmel
相关产品推荐
相关产品推荐

