Groesbeek, view of the 'National Liberation Museum 1944-1945' in Groesbeek. © Ton Kersten
Fork me on GitHub
Posts tagged as loop

Ansible, loop in loop in loop in loop in loop

2018-06-08 (147) by Ton Kersten, tagged as ansible, loop, sysadm

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) smiley

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

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

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

    - name: show all found files
        msg: "Files is {{ item.1.path }}"
        - "{{ 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) }}"