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

时间:2017-01-16 00:21:35

标签: ansible ansible-2.x ansible-template

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

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

5 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:6)

这个答案提供了@techraf

制定的方法的工作实例

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

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

将模板文件移动到dest时,

with_filetree 维护目录结构。它会在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,同时解析所有模板。

答案 2 :(得分:2)

我做到了,而且奏效了。 \ 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' }

答案 3 :(得分:1)

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

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

答案 4 :(得分: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') }}"
相关问题