如何计算与 Ansible 中的条件匹配的哈希中某个对象的出现次数? [英] How can I count the number of occurrences of a certain object in a hash that matches a condition in Ansible?

查看:19
本文介绍了如何计算与 Ansible 中的条件匹配的哈希中某个对象的出现次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ansible 变量中给出这个列表:

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

人们会怎么做呢?

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

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

推荐答案

下面的任务创建字典

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

给予

  hpc:
    BLUE: 1
    GREEN: 1
    RED: 2

这篇关于如何计算与 Ansible 中的条件匹配的哈希中某个对象的出现次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆