'How to reference multiple sub elements using ansible?

I've got an ansible playbook with the following vars structure:

TESTS:
  - name: test1
    hosts: ['host_one', 'host_two', 'host_three']
    services: ['service1, 'service2, 'service3']
  - name: test2
    hosts: ['host_four', 'host_five', 'host_six']
    services: ['service4, 'service5, 'service6']

This is the kind of task I want to do, but of course with_subelements only allows one subkey. I've been trying to use with_nested but struggling quite a lot.

- name: check services on each host
  systemd:
     name: "{{item.1}}"
     state: started
  delegate_to: "{{item.2}}"
  with_subelements:
    - "{{TESTS}}"
    - services
    - hosts

I want each service to be checked on each of the corresponding hosts. eg.

test1: 
service1 on host_one,host_two,host_three
service2 on host_one,host_two,host_three
service3 on host_one,host_two,host_three

test2: 
service4 on host_four,host_five,host_six
service5 on host_four,host_five,host_six
service6 on host_four,host_five,host_six


Solution 1:[1]

when to tranform data is complex i prefer to use a custom plugin:

create a file my_filter.py in the folder filter_plugins (same level than your playbook) and give customfilter as name:

my_filter.py:

#!/usr/bin/python
class FilterModule(object):
    def filters(self):
        return {
            'customfilter': self.customfilter
        }
 
    def customfilter(self, obj):
        result = []
        for rec in obj:
            for ser in rec["services"]:
                for host in rec["hosts"]:
                    result.append({ "name":rec["name"], "service":ser, "host":host })
        #print(result)
        return result

playbook to use the custom filter:

- name: "make this working"
  hosts: localhost

  vars:
    TESTS:
      - name: test1
        hosts: ['host_one', 'host_two', 'host_three']
        services: ['service1', 'service2', 'service3']
      - name: test2
        hosts: ['host_four', 'host_five', 'host_six']
        services: ['service4', 'service5', 'service6']

  tasks:
    - name: Debug
      debug:
        msg: "{{ item }}"
      loop: "{{ TESTS | customfilter }}"

for your playbook:

- name: check services on each host: {{ item.name }}
  systemd:
     name: "{{item.service}}"
     state: started
  delegate_to: "{{item.host}}"
  loop: "{{ TESTS | customfilter }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frenchy