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

Viewed 238

Given this list in an ansible variable:

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

I now want to count somehow the number of hosts in each cluster. So I want to end up with:

hosts_per_cluster:
   RED: 2
   BLUE: 1
   GREEN: 1

How would one go about this?

My first attempt was something like this:

- 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 }}"

That did however not work...

1 Answers

The task below creates the dictionary

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

gives

  hpc:
    BLUE: 1
    GREEN: 1
    RED: 2
Related