首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用ansible模板模块迭代地将模板应用于角色内模板目录中的所有文件

使用ansible模板模块迭代地将模板应用于角色内模板目录中的所有文件
EN

Stack Overflow用户
提问于 2022-03-11 00:16:59
回答 1查看 389关注 0票数 1

我正在使用ansible角色,模板非常有用。但是,我试图编写一个使用角色(任务/main.yml)来模板(不是单个文件,而是模板目录子目录下的一组文件)的剧本。假设我有这样一个角色目录结构:

代码语言:javascript
复制
-- tasks
   - main.yml
-- templates
   - file1.j2
   - file2.j2
   - dirA
      - file3.j2
      - file4.j2
      - dirB
        - file5.j2
        - file6.j2
   - dirC
      - file7.j2
      - file8.j2

给定目标上的一个位置(称为destinationDir),我想创建

代码语言:javascript
复制
 - destinationDir
   - file1
   - file2
   - dirA
      - file3
      - file4
      - dirB
        - file5
        - file6
   - dirC
      - file7
      - file8

但是,我不想在每次向结构中添加新文件时创建文件列表并更改播放。是否有一种方法可以动态地计算模板目录下的所有.j2文件,并在目标目录中调用每个模板模块(目录结构仍在使用)?我希望能够将新文件放到角色模板目录中,并运行play自动复制所有项目。我见过with_filetree,但我还没有弄清楚如何让它在它正在运行的角色的“模板”目录中查找。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-11 06:20:32

给这棵树

代码语言:javascript
复制
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

代码语言:javascript
复制
dest_dir: destinationDir

首先查找并创建目录

代码语言:javascript
复制
    - 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 }}"

给出

代码语言:javascript
复制
shell> tree destinationDir/
destinationDir/
├── dirA
│   └── dirB
└── dirC

现在查找并模板这些文件

代码语言:javascript
复制
    - 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 }}"

给出

代码语言:javascript
复制
shell> tree destinationDir/
destinationDir/
├── dirA
│   ├── dirB
│   │   ├── file5
│   │   └── file6
│   ├── file3
│   └── file4
├── dirC
│   ├── file7
│   └── file8
├── file1
└── file2
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71432284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档