Recursively Copy DIrectories with files that contain variables

So I have under my local “files” ansible folder, directories and files that are the same structure that I want on my target Linux host.

ansible.builtin.copy nicely recursively creates all sub directories and files under the “dest:” that I specify. The problem is that some of the files contain variables. As I know now, the copy module only copies as-is.

The ansible.builtin.template module will replace the {{ my_var }} with the value, but it seems like I have have a module for each and every file that contains a variable.

Is there some combination of the “copy” and “template” module I can use that will recursively copy all directories and files but ALSO replace all of the {{ vars }} in the files that have them?

template cannot do recursive actions like your suggesting. You could loop over the files though

- name: foo
  ansible.builtin.template:
    src: "{{ item }}"
    dest: /tmp/{{ item }}
  loop:
    - bizz/buzz.yml
    - bizz/baz.yml
    - fizz.yml

You can pair this with the fileglob lookup if you have a lot of files but it gets messy IMO. Something like this, maybe:

- name: foo
  ansible.builtin.template:
    src: "{{ item }}"
    dest: /tmp/{{ item | replace(playbook_dir + '/templates/', '') }}
  with_fileglob:
    - {{ playbook_dir }}/templates/bizz/*.yml"
2 Likes

I had a need for this on several occasions, I ended up creating a role for this:

1 Like