12

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
alex
  • 6,818
  • 9
  • 52
  • 103
Jean Peuxplus
  • 121
  • 1
  • 1
  • 4

4 Answers4

25

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]
Prash
  • 558
  • 5
  • 8
4

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.

garnaat
  • 44,310
  • 7
  • 123
  • 103
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
Murphy
  • 536
  • 6
  • 13
0

A simple way to retrieve volumes would be as follows

ec2 = boto3.resource('ec2',"us-west-1")
volume = ec2.volumes.all()
for vol in volume:
    print(vol.id)
    print(vol.tags)
Marcus
  • 2,153
  • 2
  • 13
  • 21
T_Square
  • 23
  • 6