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

如何从AWS EC2实例JSON响应中提取CPU参数并计算总vCPUs

解决AWS EC2运行实例vCPU汇总问题

实现步骤

  • 遍历API返回的层级结构:从Reservations数组逐层进入每个Instance对象
  • 提取CPU配置参数:从实例的CpuOptions字段中取出CoreCount和ThreadsPerCore
  • 计算单实例vCPU值:通过CoreCount × ThreadsPerCore得到单个实例的vCPU数量
  • 累加总vCPU:维护一个全局累加变量,将每个实例的vCPU值依次加入

完整代码实现

import boto3

def get_total_running_vcpus():
    ec2 = boto3.client('ec2')
    # 获取所有处于运行状态的EC2实例数据
    response = ec2.describe_instances(
        Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
    )
    
    total_vcpus = 0
    
    # 双层循环遍历Reservation和Instance层级
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            # 安全提取CPU参数,避免字段缺失报错
            cpu_options = instance.get('CpuOptions', {})
            core_count = cpu_options.get('CoreCount', 0)
            threads_per_core = cpu_options.get('ThreadsPerCore', 0)
            
            # 计算单实例vCPU并累加
            instance_vcpus = core_count * threads_per_core
            total_vcpus += instance_vcpus
            
            # 可选:打印单个实例的vCPU信息
            print(f"实例ID {instance['InstanceId']}: {instance_vcpus} vCPU")
    
    print(f"\n所有运行中实例总vCPU数: {total_vcpus}")
    return total_vcpus

# 执行计算逻辑
get_total_running_vcpus()

关键细节说明

  • 使用dict.get()替代直接索引:防止部分实例因缺少CpuOptions字段导致程序崩溃,默认值设为0保证计算流程不中断
  • 适配AWS API结构:DescribeInstances返回的顶层结构是Reservations数组,每个Reservation下包含多个Instances,必须通过双层循环遍历所有实例
  • 累加变量初始化:在循环外部初始化total_vcpus = 0,确保每次循环都能正确累加数值

示例输出

实例ID i-1234567890abcdef0: 4 vCPU
实例ID i-0abcdef1234567890: 4 vCPU

所有运行中实例总vCPU数: 8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:15:21