How do you loop over files?
IntermediateConceptJinja2, Conditionals and Loops
Answer
For files on the control node use the fileglob lookup. For files on the target use the find module and loop over its results.
- ansible.builtin.copy:
src: "{{ item }}"
dest: /etc/app/conf.d/
loop: "{{ lookup('ansible.builtin.fileglob', 'files/conf.d/*.conf', wantlist=true) }}"
- ansible.builtin.find: { paths: /var/log/app, patterns: '*.log', age: 14d }
register: old
- ansible.builtin.file: { path: "{{ item.path }}", state: absent }
loop: "{{ old.files }}"
For a whole tree, synchronize or copy with a directory src is faster than looping.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner