List EC2 volumes in Boto

风格不统一 提交于 2019-12-23 10:25:14

问题


I want to list all volumes attached to my 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}))

With my code I can list volume but the result is like that :

[vol-35b0b5fa, Volume:vol-6cbbbea3]

I need something like :

vol-35b0b5fa

vol-6cbbbea3

I don't know how i can do, and my research don"t help me.

Somebody can help me please ?


回答1:


If you are using Boto3 library then here is the command to list out all attached volumes

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]



回答2:


The get_all_volumes call in boto returns a list of Volume objects. If all you need is the ID of the volume, you can get that using the id attribute of the Volume object:

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

The variable volume_ids would now be a list of strings where each string is the ID of one of the volumes.




回答3:


I think here the requirement is just to iterate over the list with v.id: Just add this to your code:

for v in volumes:
    print v.id


来源:https://stackoverflow.com/questions/34002826/list-ec2-volumes-in-boto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!