Ansible, loop in loop in loop in loop in loop


A couple of days ago a client asked me if I could solve the following problem:

They have a large number of web servers, all running a plethora of PHP versions. These machines are locally managed with DirectAdmin, which manages the PHP configuration files as well. They are also running Ansible for all kind of configuration tasks. What they want is a simple playbook that ensures a certain line in all PHP ini files for all PHP versions on all webservers.

All the PHP directories match the pattern /etc/php[0-9][0-9].d.

Thinking about this, I came up with this solution (took me some time, though) :-)

---
- name: find all ini files in all /etc/php directories
  hosts: webservers
  user: ansible
  become: True
  become_user: root

  tasks:
    - name: get php directories
      find:
        file_type: directory
        paths:
          - /etc
        patterns:
           - php[0-9][0-9].d
      register: dirs

    - name: get files in php directories
      find:
        paths:
          - "{{ item.path }}"
        patterns:
          - "*.ini"
      loop: "{{ dirs.files }}"
      register: phpfiles

    - name: show all found files
      debug:
        msg: "Files is {{ item.1.path }}"
      with_subelements:
        - "{{ phpfiles.results }}"
        - files

The part with the with_subelements did the trick. Of course this line can be written as:

loop: "{{ query('subelements', phpfiles.results, files) }}"

See also