Ansible: generating content for all template files using with_fileglob

There are scenarios where instead of being explicit about each file name when generating templates from a role, you may want to take all the suffixed files in the ‘templates’ directory and dump their generated content into a destination directory.

As a quick example, if you are in a role and want every script in the templates directory ending with ‘.sh’ to generate a file then use ‘with_fileglob’ like below.

 - name: create file out of every file in template directory
   template:
     src: "{{item}}"
     dest: /tmp/.
   with_fileglob: "{{role_path}}/templates/*.sh"

If your templates have an additional suffix tacked on (such as ‘.j2’), then you can use the jinja2 regex_replace to strip it off like below.

 - name: create file out of every jinja2 template
   template:
     src: "{{item}}"
     dest: /tmp/{{ item | basename | regex_replace('\.j2$', '') }}
   with_fileglob: "{{role_path}}/templates/*.j2"

Here is a link to a playbook using the role, which can be invoked locally for testing:

ansible-playbook playbook-fileglob.yml --connection=local

Here is a link to the full fileglobtest role.

 

REFERENCES

stackoverflow Margaret, with_fileglob for generating template content from directory

ansible docs, fileglob

ansible docs, playbook filters

ansible docs, special variables including ‘role_path’

webforefront.com, many examples of built-in jinja2 filters