我正在使用ansible角色,模板非常有用。但是,我试图编写一个使用角色(任务/main.yml)来模板(不是单个文件,而是模板目录子目录下的一组文件)的剧本。假设我有这样一个角色目录结构:
-- tasks
- main.yml
-- templates
- file1.j2
- file2.j2
- dirA
- file3.j2
- file4.j2
- dirB
- file5.j2
- file6.j2
- dirC
- file7.j2
- file8.j2给定目标上的一个位置(称为destinationDir),我想创建
- destinationDir
- file1
- file2
- dirA
- file3
- file4
- dirB
- file5
- file6
- dirC
- file7
- file8但是,我不想在每次向结构中添加新文件时创建文件列表并更改播放。是否有一种方法可以动态地计算模板目录下的所有.j2文件,并在目标目录中调用每个模板模块(目录结构仍在使用)?我希望能够将新文件放到角色模板目录中,并运行play自动复制所有项目。我见过with_filetree,但我还没有弄清楚如何让它在它正在运行的角色的“模板”目录中查找。
发布于 2022-03-11 06:20:32
给这棵树
shell> tree templates/
templates/
├── dirA
│ ├── dirB
│ │ ├── file5.j2
│ │ └── file6.j2
│ ├── file3.j2
│ └── file4.j2
├── dirC
│ ├── file7.j2
│ └── file8.j2
├── file1.j2
└── file2.j2和变量dest_dir
dest_dir: destinationDir首先查找并创建目录
- find:
path: templates
file_type: directory
recurse: true
register: result
- file:
state: directory
path: "{{ dest_dir }}/{{ _path }}"
loop: "{{ result.files|map(attribute='path')|list }}"
vars:
_path: "{{ item.split('/', 1)|last }}"给出
shell> tree destinationDir/
destinationDir/
├── dirA
│ └── dirB
└── dirC现在查找并模板这些文件
- find:
path: templates
recurse: true
register: result
- template:
src: "{{ _src }}"
dest: "{{ dest_dir }}/{{ _dest }}"
loop: "{{ result.files|map(attribute='path')|list }}"
vars:
_src: "{{ item.split('/', 1)|last }}"
_dest: "{{ _src|splitext|first }}"给出
shell> tree destinationDir/
destinationDir/
├── dirA
│ ├── dirB
│ │ ├── file5
│ │ └── file6
│ ├── file3
│ └── file4
├── dirC
│ ├── file7
│ └── file8
├── file1
└── file2https://stackoverflow.com/questions/71432284
复制相似问题