You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ansible确定数组中出现频率最高的VLAN值

用Ansible统计数组中出现频率最高的VLAN值

我来帮你实现从IOS设备返回的配置中统计出现频率最高的VLAN的需求,下面是完整的任务步骤和细节解释:

完整的Ansible任务流程

tasks:
  - name: 查找高频VLAN
    ios_command:
      provider: "{{ cli }}"
      commands:
        - show run | i switchport access vlan
    register: sh_res

  - name: 提取所有VLAN号
    set_fact:
      vlan_list: "{{ sh_res.stdout_lines[0] | map('regex_replace', '.*vlan (\\d+)', '\\1') | list }}"

  - name: 统计每个VLAN的出现次数
    set_fact:
      vlan_counts: "{{ vlan_counts | default({}) | combine({ item: (vlan_counts[item] | default(0)) + 1 }) }}"
    loop: "{{ vlan_list }}"

  - name: 确定出现频率最高的VLAN
    set_fact:
      most_frequent_vlan: "{{ vlan_counts | dict2items | sort(attribute='value', reverse=True) | first }}"

  - name: 输出高频VLAN结果
    debug:
      msg: "出现频率最高的VLAN是*{{ most_frequent_vlan.key }}*,总共出现了{{ most_frequent_vlan.value }}次"

步骤详解

1. 提取纯VLAN号

首先我们需要从命令输出的每行文本中提取出VLAN数字:

  • sh_res.stdout_lines[0]:因为ios_command返回的stdout_lines是二维数组,第一个元素就是命令输出的所有行内容
  • map('regex_replace', '.*vlan (\\d+)', '\\1'):遍历每一行,用正则匹配vlan关键字后的数字部分,只保留纯VLAN号
  • 最后用list把处理结果转成数组,得到所有VLAN号的列表vlan_list

2. 统计VLAN出现次数

通过循环遍历VLAN列表,用字典来记录每个VLAN的出现频次:

  • default({}):第一次循环时初始化一个空字典
  • combine({ item: (vlan_counts[item] | default(0)) + 1 }):每次循环更新字典,把当前VLAN的计数加1(如果是首次出现就从0开始累加)

3. 定位高频VLAN

把统计好的字典转换成键值对列表,按出现次数倒序排序后取第一个元素,就是频率最高的VLAN:

  • dict2items:把vlan_counts字典转换成[{key: '22', value: 8}, ...]的列表格式
  • sort(attribute='value', reverse=True):按value(出现次数)从高到低排序
  • first:取排序后的第一个元素,即为出现次数最多的VLAN

特殊情况处理

如果有多个VLAN出现次数相同且都是最高值,上面的任务会取排序后的第一个VLAN。如果需要列出所有最高频率的VLAN,可以修改最后一步的逻辑:

- name: 确定所有出现频率最高的VLAN
  set_fact:
    max_count: "{{ vlan_counts.values() | max }}"
    top_vlans: "{{ vlan_counts | dict2items | selectattr('value', 'equalto', max_count) | map(attribute='key') | list }}"

- debug:
    msg: "出现频率最高的VLAN有{{ top_vlans }},均出现{{ max_count }}次"

内容的提问来源于stack exchange,提问作者Vladimir Fomin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:01:22