Python 在Boto中列出EC2卷

Python 在Boto中列出EC2卷,python,amazon-web-services,amazon-ec2,boto,Python,Amazon Web Services,Amazon Ec2,Boto,我想列出连接到我的EC2实例的所有卷 我可以用我的代码列出卷: conn = EC2Connection() attribute = get_instance_metadata() region=attribute['local-hostname'].split('.')[1] inst_id = attribute['instance-id'] aws = boto.ec2.connect_to_region(region) volume=attribute['local-hostname']

我想列出连接到我的EC2实例的所有卷

我可以用我的代码列出卷:

conn = EC2Connection()
attribute = get_instance_metadata()
region=attribute['local-hostname'].split('.')[1]
inst_id = attribute['instance-id']
aws = boto.ec2.connect_to_region(region)
volume=attribute['local-hostname']
volumes = str(aws.get_all_volumes(filters={'attachment.instance-id': inst_id}))
但这导致:

[vol-35b0b5fa, Volume:vol-6cbbbea3]
我需要像这样的东西:

vol-35b0b5fa
vol-6cbbbea3

boto中的
get\u all\u volumes
调用返回
Volume
对象列表。如果您只需要卷的ID,则可以使用
volume
对象的
ID
属性来获取:

import boto.ec2
ec2 = boto.ec2.connect_to_region(region_name)
volumes = ec2.get_all_volumes()
volume_ids = [v.id for v in volumes]

变量
volume\u ID
现在将是一个字符串列表,其中每个字符串都是其中一个卷的ID。

我认为这里的要求只是使用v.ID对列表进行迭代: 只需在代码中添加以下内容:

for v in volumes:
    print v.id

如果您使用的是Boto3库,那么下面是列出所有连接卷的命令

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
volumes = ec2.volumes.all() # If you want to list out all volumes
volumes = ec2.volumes.filter(Filters=[{'Name': 'status', 'Values': ['in-use']}]) # if you want to list out only attached volumes
[volume for volume in volumes]

要使其更短,只需执行[v.id for v in volumes]