ansibleansible-2.xansible-template

Can the templates module handle multiple templates / directories?


I believe the Ansible copy module can take a whole bunch of "files" and copy them in one hit. This I believe can be achieved by copying a directory recursively.

Can the Ansible template module take a whole bunch of "templates" and deploy them in one hit? Is there such a thing as deploying a folder of templates and applying them recursively?


Solution

  • 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.