Interview Prep/Ansible/Jinja2, Conditionals and Loops

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.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops