如何计算某个对象在与 Ansible 中的条件匹配的散列中出现的次数?

How can I count the number of occurrences of a certain object in a hash that matches a condition in Ansible?

在 ansible 变量中给定此列表:

---
hosts:
- address: host1.local
  cluster:
    name: RED
- address: host2.local
  cluster:
    name: RED
- address: host3.local
  cluster:
    name: GREEN
- address: host4.local
  cluster:
    name: BLUE

我现在想以某种方式计算每个集群中的主机数量。所以我想结束:

hosts_per_cluster:
   RED: 2
   BLUE: 1
   GREEN: 1

怎么办?

我的第一次尝试是这样的:

- name: Get number of hosts per cluster
      set_fact: 
        hosts_per_cluster[item.cluster.name]={{ hosts_per_cluster[item.cluster.name] | default(0) | int +1 }}
      loop: "{{ hosts }}"

但是没有用...

下面的任务创建字典

    - set_fact:
        hpc: "{{ hpc|default({})|combine({item.0: item.1|length}) }}"
      loop: "{{ _hosts|groupby('cluster.name') }}"

给予

  hpc:
    BLUE: 1
    GREEN: 1
    RED: 2