计算ansible列表中每个唯一元素的出现次数

Count number of occurrences of each unique element in a list in ansible

如何计算列表中每个项目重复了多少次?

    ok: [] => {
        "list": [
            "5.8.3",
            "5.8.4",
            "5.8.4",
            "5.9.2",
            "5.9.2",
            "5.9.2"
        ]
    }
    

我想打印这样的东西:

    ok: [] => {
        "list_counter": [
            "5.8.3": 1
            "5.8.4": 2
            "5.9.2": 3
        ]
    }

我试过类似的方法,但没有成功

    - set_fact:
        list_counter: '{{ item : 1 + item.get(unique_int[item],0) }}'
      loop: "{{ list }}" 

使用community.general.counter if you can install latest collection Community.General

list_counter: "{{ list|community.general.counter }}"

给出了预期的结果

list_counter:
  5.8.3: 1
  5.8.4: 2
  5.9.2: 3

如果您无法安装该集合,请使用 code 并创建自定义过滤器插件

shell> cat filter_plugins/my_counter.py 
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Remy Keil <remy.keil@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.errors import AnsibleFilterError
from ansible.module_utils.common._collections_compat import Sequence
from collections import Counter


def my_counter(sequence):
    ''' Count elements in a sequence. Returns dict with count result. '''
    if not isinstance(sequence, Sequence):
        raise AnsibleFilterError('Argument for community.general.counter must be a sequence (string or list). %s is %s' %
                                 (sequence, type(sequence)))

    try:
        result = dict(Counter(sequence))
    except TypeError as e:
        raise AnsibleFilterError(
            "community.general.counter needs a sequence with hashable elements (int, float or str) - %s" % (e)
        )
    return result


class FilterModule(object):
    ''' Ansible counter jinja2 filters '''

    def filters(self):
        filters = {
            'my_counter': my_counter,
        }

        return filters

使用它

    - set_fact:
        list_count: "{{ list|my_counter }}"