title: How can I count the number of occurrences of a certain object in a hash that matches a condition in Ansible?
body: <p>Given this list in an ansible variable:</p>
  <pre class="lang-yaml prettyprint-override"><code>---
  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
  </code></pre>
  <p>I now want to count somehow the number of hosts in each cluster. So I want to end up with:</p>
  <pre><code>hosts_per_cluster:
     RED: 2
     BLUE: 1
     GREEN: 1
  </code></pre>
  <p>How would one go about this?</p>
  <p>My first attempt was something like this:</p>
  <pre><code>- 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: &quot;{{ hosts }}&quot;
  </code></pre>
  <p>That did however not work...</p>