I want to recursively copy over a directory and render all .j2 files in there as templates. For this I am currently using the following lines:
Usually I do not remove files but I add -unmanaged
suffix to its name.
Sample ansible tasks:
- name: Get sources.list.d files
shell: grep -r --include=\*.list -L '^# Ansible' /etc/apt/sources.list.d || true
register: grep_unmanaged
changed_when: grep_unmanaged.stdout_lines
- name: Add '-unmanaged' suffix
shell: rename 's/$/-unmanaged/' {{ item }}
with_items: grep_unmanaged.stdout_lines
EXPLANATION
Grep command uses:
-r
to do recursive search --include=\*.list
- only take files
with .list extension during recursive search -L '^# Ansible'
- display file names that are not having line starting with '# Ansible'|| true
- this is used to ignore errors. Ansible's ignore_errors
also works but before ignoring the error ansible will show it in red color during ansible-playbook run
which is undesired (at least for me).Then I register output of grep command as a variable. When grep displays any output I set this task as changed (the line changed_when
is responsible for this).
In next task I iterate grep output (i.e. file names returned by grep) and run rename command to add suffix to each file.
That's all. Next time you run the command first task should be green and second skipped.