Can the templates module handle multiple templates / directories?

The template module itself runs the action on a single file, but you can use with_filetree to loop recursively over a specified path:

- name: Ensure directory structure exists
  ansible.builtin.file:
    path: '{{ templates_destination }}/{{ item.path }}'
    state: directory
  with_community.general.filetree: '{{ templates_source }}'
  when: item.state == 'directory'

- name: Ensure files are populated from templates
  ansible.builtin.template:
    src: '{{ item.src }}'
    dest: '{{ templates_destination }}/{{ item.path }}'
  with_community.general.filetree: '{{ templates_source }}'
  when: item.state == 'file'

And for templates in a single directory you can use with_fileglob.


This answer provides a working example of the approach laid down by @techraf

with_fileglob expects only files to live within the templates folder - see https://serverfault.com/questions/578544/deploying-a-folder-of-template-files-using-ansible

with_fileglob will only parse files in the templates folder

with_filetree maintains the directory structure when moving the template files to dest. It auto creates those directories for you at dest.

with_filetree will parse all files in the templates folder and nested directories

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

Essentially, think of this approach as copying and pasting a directory and all its contents from A to B and whilst doing so, parsing all templates.


In my case folder contain both files and jinja2 templates.

- 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') }}"

I could not manage to do it with the other answers. This is what worked for me:

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