13

我相信 Ansible复制模块可以获取一大堆“文件”并一次复制它们。我相信这可以通过递归复制目录来实现。

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

4

5 回答 5

52

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'

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

于 2017-01-16T00:44:38.670 回答
11

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

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

with_fileglob 只会解析模板文件夹中的文件

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

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

- 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'

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

于 2017-01-16T01:56:07.760 回答
3

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

- 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'
于 2020-11-30T16:39:32.083 回答
1

我做到了,它奏效了。\o/

- name: "Create file template"
  template:
    src: "{{ item.src }}"
    dest: "{{ your_dir_remoto }}/{{ item.dest }}"
  loop:
    - { src: '../templates/file1.yaml.j2', dest: 'file1.yaml' }
    - { src: '../templates/file2.yaml.j2', dest: 'file2.yaml' }
于 2020-08-25T13:24:58.603 回答
1

在我的案例中,文件夹包含文件和 jinja2 模板。

- name: copy all directories recursively
  file: dest={{templates_dest_path}}/{{ item|replace(templates_src_path+'/', '') }}  state=directory       
  with_items: "{{ lookup('pipe', 'find '+ templates_src_path +'/ -type d').split('\n') }}"

- name: copy all files recursively
  copy: src={{ item }} dest={{templates_dest_path}}/{{ item|replace(templates_src_path+'/', '') }} 
  with_items: "{{ lookup('pipe', 'find '+ templates_src_path +'/  -type f -not -name *.j2 ').split('\n') }}"
  
- name: copy templates files recursively
  template: src={{ item }} dest={{templates_dest_path}}/{{ item|replace(templates_src_path+'/', '')|replace('.j2', '') }}  
  with_items: "{{ lookup('pipe', 'find '+ templates_src_path +'/*.j2 -type f').split('\n') }}"
于 2021-08-04T19:35:01.727 回答