首页 > 解决方案 > AWS 提取卷 AttachmentID Boto3

问题描述

我需要在我的帐户中生成所有 ebs 卷和实例附件的列表。我知道如何做到这一点,但我想使用 Python。如何提取我账户中所有正在使用的卷的附件 ID?

    # Get all in-use volumes in all regions  
    result = ec2.describe_volumes( Filters=[{'Name': 'status', 'Values': ['in-use']}])
    for volume in result['Volumes']:
        attachment = ec2.describe_volumes().get('AttachmentsID,[]')
        print(attachment)

标签: pythonamazon-web-servicesamazon-ec2boto3

解决方案


describe_volumes()已经返回您需要的信息'Attachments'。要打印所有卷,您需要查询所有区域并处理分页。

import boto3
import botocore.exceptions

session = boto3.Session()
for region in session.get_available_regions('ec2'):
    print(region)
    try:
        ec2 = session.client('ec2', region_name=region)
        for res in ec2.get_paginator('describe_volumes').paginate(Filters=[{'Name': 'status', 'Values': ['in-use']}]):
            for volume in res['Volumes']:
                for attachment in volume['Attachments']:
                    print(attachment['InstanceId'], attachment['VolumeId'])
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == 'AuthFailure':
            print('No access to', region)
        else:
            raise

推荐阅读