我使用Ansible为各种应用程序(基于group_names)推送配置文件&需要从列表变量循环通过配置.j2模板。如果我使用已知的配置模板列表,我可以使用这样的标准with_nested .
template:
src: '{{ playbook_dir }}/templates/{{ item[1] }}/configs/{{ item[0] }}.j2'
dest: /path/to/{{ item[1] }}/configs/{{ item[0] }}
with_nested:
- ['file.1', 'file.2', 'file.3', 'file.4']
- '{{ group_names }}'然而,由于每个应用程序都有自己的秘密,所以我不能使用一个通用的with_nested列表。任何使用with_filetree嵌套的尝试都失败了。有什么方法可以嵌套with_filetree吗?我是不是错过了一些显而易见的痛苦?
发布于 2020-09-30 08:08:39
处理这一问题的最直接的方法可能是通过包含来重复循环。我认为您的应用程序目录只包含.j2文件是理所当然的。如果不是这样的话,就调整一下。
在例如push_templates.yml中
---
- name: Copy templates for group {{ current_group }}
template:
src: "{{ item.src }}"
dest: /path/to/{{ current_group }}/configs/{{ (item.src | splitext).0 | basename }}
with_filetree: "{{ playbook_dir }}/templates/{{ current_group }}"
# Or using the latest loop syntax
# loop: "{{ query('filetree', playbook_dir + '/templates/' + current_group) }}"
when: item.src is defined注意:在dest行上,我删除了文件的最后一个找到的扩展名,并且只获取它的名称,而没有前面的目录路径。查看过滤器上的不可接受的文档中的splitext和basename获取更多信息
然后在你的例子中比如main.yml
- name: Copy templates for all groups
include_tasks: push_templates.yml
loop: "{{ group_names }}"
loop_control:
loop_var: current_group注意控制部分中的loop_var,以消除包含的文件中可能出现的item重叠。当然,var名称与我在上面包含的文件中使用的名称是对齐的。有关更多信息,请参见不可测循环文档。
解决上述问题的另一种方法是构建您自己的数据结构,使用set_fact在您的组上循环,并在每次迭代中调用filetree查找(请参阅上面使用更新的loop语法的示例),然后循环您的自定义数据结构来完成这项工作。
https://stackoverflow.com/questions/64127912
复制相似问题