亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕后森 2023-09-12 19:52:09
我正在嘗試使用 python 獲取 EC2 中的 EBS 卷列表。這是我的代碼:import boto3import objectpathaws_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 卷及其大小的列表。我怎樣才能做到這一點?
查看完整描述

1 回答

?
小唯快跑啊

TA貢獻1863條經驗 獲得超2個贊

“我想獲取任何給定 EC2 實例的 EBS 卷及其大小的列表。”


這是使用該resource方法的代碼:


import boto3


ec2_resource = boto3.resource('ec2')


for instance in ec2_resource.instances.all():

    for volume in instance.volumes.all():

        print(instance.id, volume.id, volume.volume_type, volume.size)

并使用client方法:


import boto3


ec2_client = boto3.client('ec2')


response = ec2_client.describe_instances()


for reservation in response['Reservations']:

    for instance in reservation['Instances']:

        volumes = ec2_client.describe_volumes(

            Filters=[{'Name':'attachment.instance-id','Values':[instance['InstanceId']]}]

        )

        for disk in volumes['Volumes']:

            print(instance['InstanceId'], disk['VolumeId'], disk['VolumeType'], disk['Size'])

但是,這會導致多次 API 調用(每個實例DescribeInstances()一次調用)。DescribeVolumes()


此版本僅使用一次調用DescribeVolumes()并按 InstanceId 排序:


import boto3


ec2_resource = boto3.resource('ec2')


volumes = [(v.attachments[0]['InstanceId'], v.id, v.size)

           for v in ec2_resource.volumes.filter(Filters=[{'Name':'attachment.status','Values':['attached']}])]


for volume in sorted(volumes):

    print(volume[0], volume[1], volume[2])

下面是使用該方法的等效代碼client:


import boto3


ec2_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):

    print(volume[0], volume[1], volume[2])

除了根據本網站服務條款授予的許可之外,本文的內容還根據 MIT-0 獲得許可。


查看完整回答
反對 回復 2023-09-12
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號