模板模块可以处理多个模板/目录吗?

dan*_*y74 5 ansible ansible-template ansible-2.x

我相信Ansible 复制模块可以采用一大堆"文件"并在一次点击中复制它们.我相信这可以通过递归复制目录来实现.

Ansible 模板模块可以采用一大堆"模板"并在一次点击中部署它们吗?是否存在部署模板文件夹并递归应用它们的事情?

tec*_*raf 28

template模块本身运行在单个文件的操作,但你可以使用with_filetree递归在指定的路径循环:

- name: Ensure directory structure exists
  file:
    path: '{{ templates_destination }}/{{ item.path }}'
    state: directory
  with_filetree: '{{ templates_source }}'
  when: item.state == 'directory'

- name: Ensure files are populated from templates
  template:
    src: '{{ item.src }}'
    dest: '{{ templates_destination }}/{{ item.path }}'
  with_filetree: '{{ templates_source }}'
  when: item.state == 'file'
Run Code Online (Sandbox Code Playgroud)

对于单个目录中的模板,您可以使用with_fileglob.

  • 当一个计划汇集在一起​​时,我喜欢它! (2认同)

小智 8

我无法用其他答案来做到这一点。这对我有用:

- name: Template all the templates and place them in the corresponding path
  template:
    src: "{{ item.src }}"
    dest: "{{ destination_path }}/{{ item.path | regex_replace('\\.j2$', '') }}"
    force: yes
  with_filetree: '{{ role_path }}/templates'
  when: item.state == 'file'
Run Code Online (Sandbox Code Playgroud)


dan*_*y74 7

这个答案提供了@techraf制定的方法的工作示例

with_fileglob只希望文件存在于templates文件夹中 - 请参阅https://serverfault.com/questions/578544/deploying-a-folder-of-template-files-using-ansible

with_fileglob只会解析templates文件夹中的文件

with_filetree在将模板文件移动到dest时维护目录结构.它会在dest为您自动创建这些目录.

with_filetree将解析templates文件夹和嵌套目录中的所有文件

- name: Approve certs server directories
  file:
    state: directory
    dest: '~/{{ item.path }}'
  with_filetree: '../templates'
  when: item.state == 'directory'

- name: Approve certs server files
  template:
    src: '{{ item.src }}'
    dest: '~/{{ item.path }}'
  with_filetree: '../templates'
  when: item.state == 'file'
Run Code Online (Sandbox Code Playgroud)

从本质上讲,将此方法视为将目录及其所有内容从A复制并粘贴到B,同时解析所有模板.

  • 如果"它自动为你创建那些目录",为什么需要预先创建目录 (3认同)