如何获取AWS Boto Python EC2实例中的vCPU数量?

时间:2019-08-06 10:15:02

标签: python amazon-web-services amazon-ec2 aws-sdk boto

是否可以通过boto python API获取EC2实例中的vCPU(内核)数量?

到目前为止,我的代码是:

在boto3中找到了它:

import boto3     
ec2 = boto3.resource('ec2', region_name=REGION_NAME)
instance = ec2.Instance(id)
instance.cpu_options.get(u'CoreCount','1')

返回的是我的物理核数,但是通过htop,我可以看到我的核芯数是VCPU的两倍,是否总是这样?也许与ThreadsPerCore的数量有关?

1 个答案:

答案 0 :(得分:0)

我是用这种方式完成的,需要最新版本的boto3:

import boto3
# You may have to update boto3 to get this to work, describe_instance_types is quite new:
# pip install boto3 --upgrade
ec2 = boto3.client('ec2')

reservations = ec2.describe_instances()['Reservations']
vcpus = 0
for reservation in reservations:
    for instance in reservation['Instances']:
        instance_id = instance['InstanceId']
        instance_type_name = instance['InstanceType']
        instance_type = ec2.describe_instance_types(InstanceTypes=[instance_type_name])
        current_vcpu_count = instance_type['InstanceTypes'][0]['VCpuInfo']['DefaultVCpus']
        print(f'{instance_id} - {instance_type_name} - {current_vcpu_count}')
        vcpus += current_vcpu_count

print(vcpus)