---
- name: Count Docker containers and execute tasks and/or roles on host with fewer containers
  hosts: my-hosts

  tasks:
    - name: Count number of Docker containers on each host
      shell: "docker ps -q | wc -l"
      register: container_count
      changed_when: false

    - name: Find the host with the minimum number of containers
      set_fact:
        max_container_host: "{{ ansible_play_hosts| map('extract', hostvars, 'container_count') | map(attribute='stdout') | map('int') | max | int }}"
      delegate_to: localhost
      run_once: true

    - name: Debug max_container_host
      debug:
        msg: "Largest number of containers running is {{ max_container_host }}"
      delegate_to: localhost
      run_once: true


  post_tasks:
    - name: Execute post-task on the host with fewer containers
      debug:
        msg: "This is the host with fewer containers: {{ inventory_hostname }}"
      when: container_count.stdout < max_container_host

    - name: Include multiple roles
      include_role: 
        name: "{{ item }}"
      loop: 
        - my-role-1 
        - my-role-2 
      when: container_count.stdout < max_container_host
