如何使用 Python 获取 EC2 中的 EBS 卷列表

我正在尝试使用 python 获取 EC2 中的 EBS 卷列表。


这是我的代码:


import boto3

import objectpath

aws_account = 'company-lab'

region = 'us-east-1'

session = boto3.Session(profile_name=aws_account, region_name=region)

ec2 = session.client("ec2")

instance_list = ec2.describe_instances()

for reservation in instance_list["Reservations"]:

    for instance in reservation.get("Instances", []):

        tree = objectpath.Tree(instance)

        block_devices = set(tree.execute('$..BlockDeviceMappings[\'Ebs\'][\'VolumeId\']'))

        block_devices = list(block_devices)

        for volume_id in block_devices:

            volume = ec2.Volume(volume_id)

当我尝试这样做时,我收到以下错误:


Traceback (most recent call last):

  File "<stdin>", line 7, in <module>

  File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\client.py", line 573, in __getattr__

    raise AttributeError(

AttributeError: 'EC2' object has no attribute 'Volume'

我正在尝试使用boto3 EC2 卷属性。我想获取任何给定 EC2 实例的 EBS 卷及其大小的列表。我怎样才能做到这一点?



慕后森
浏览 104回答 1
1回答

小唯快跑啊

“我想获取任何给定 EC2 实例的 EBS 卷及其大小的列表。”这是使用该resource方法的代码:import boto3ec2_resource = boto3.resource('ec2')for instance in ec2_resource.instances.all():&nbsp; &nbsp; for volume in instance.volumes.all():&nbsp; &nbsp; &nbsp; &nbsp; print(instance.id, volume.id, volume.volume_type, volume.size)并使用client方法:import boto3ec2_client = boto3.client('ec2')response = ec2_client.describe_instances()for reservation in response['Reservations']:&nbsp; &nbsp; for instance in reservation['Instances']:&nbsp; &nbsp; &nbsp; &nbsp; volumes = ec2_client.describe_volumes(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Filters=[{'Name':'attachment.instance-id','Values':[instance['InstanceId']]}]&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; for disk in volumes['Volumes']:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(instance['InstanceId'], disk['VolumeId'], disk['VolumeType'], disk['Size'])但是,这会导致多次 API 调用(每个实例DescribeInstances()一次调用)。DescribeVolumes()此版本仅使用一次调用DescribeVolumes()并按 InstanceId 排序:import boto3ec2_resource = boto3.resource('ec2')volumes = [(v.attachments[0]['InstanceId'], v.id, v.size)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;for v in ec2_resource.volumes.filter(Filters=[{'Name':'attachment.status','Values':['attached']}])]for volume in sorted(volumes):&nbsp; &nbsp; print(volume[0], volume[1], volume[2])下面是使用该方法的等效代码client:import boto3ec2_client = boto3.client('ec2')response = ec2_client.describe_volumes(Filters=[{'Name':'attachment.status','Values':['attached']}])volumes = [(v['Attachments'][0]['InstanceId'], v['VolumeId'], v['Size']) for v in response['Volumes']]for volume in sorted(volumes):&nbsp; &nbsp; print(volume[0], volume[1], volume[2])除了根据本网站服务条款授予的许可之外,本文的内容还根据 MIT-0 获得许可。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python