Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List EC2 volumes in Boto

I want to list all volumes attached to my EC2 instance.

I can list volumes with my code:

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}))

But this results in:

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

I need something like:

vol-35b0b5fa
vol-6cbbbea3
like image 393
Jean Peuxplus Avatar asked Nov 30 '15 16:11

Jean Peuxplus


2 Answers

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]
like image 63
Prash Avatar answered Sep 19 '22 00:09

Prash


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.

like image 24
garnaat Avatar answered Sep 23 '22 00:09

garnaat