4

I am trying to get volume-id list of aws instance using boto 3, I am getting sort of collection manager but I don't know how to get the data inside.

import boto3
ec2 = boto3.resource('ec2', region_name='us-west-2')
instance = ec2.Instance('i-xxxxxx')
volumes = instance.volumes.all()
print volumes

The answer I got is:

ec2.Instance.volumesCollection(ec2.Instance(id='i-xxxxxx'), ec2.Volume)

How I am using the "ec2.Volume" to get the volume id

Thanks, Cfir.

cfircoo
  • 407
  • 2
  • 8
  • 20

5 Answers5

7

It's just an iterable of objects so

for v in volumes:
    print(v.id)

if you want to get a list of id :

l = [v.id for v in volumes]
polku
  • 1,525
  • 2
  • 15
  • 11
3

An iterator is returned by ec2.Instance.volumesCollection

You can extract the volume ids with code like this

volume_id_list=[]
for item in instance.volumes.all():
  volume_id_list.append(item.id)

then volume_id_list[0] contains the first disk, volume_id_list[1] the second etc

See https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.volumes

Vorsprung
  • 30,988
  • 4
  • 36
  • 58
3

Using an EC2 client:

ec2_client = boto3.client('ec2',
                    aws_access_key_id='XYZ',
                    aws_secret_access_key='XYZ',
                    region_name='us-east-1')
volumes = ec2_client.describe_instance_attribute(InstanceId='i-0b30bea4e05579def',
Attribute='blockDeviceMapping')
Montaro
  • 8,390
  • 5
  • 27
  • 30
1

e.g. you can get the volume ID and size simply by iterating over it.

for volume in volumes:
    print (volume.id, volume.size)
Maximilian Peters
  • 27,890
  • 12
  • 74
  • 90
0

You can use cli also. Example I'm trying to get list of root volumes attached

aws ec2 describe-volumes --filters "Name=attachment.device,Values=*sda1" --query "Volumes[*].[VolumeId]"  --output text --profile=my_genius_aws_profile
Impermanence
  • 106
  • 4