Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I filter volumes by instance_id in boto?

I'm trying to copy volumes from one instance to another using Python's 'boto' module. Part of that process is identifying the volumes attached to an instance. There are a couple ways to approach this problem. For example, I could use list comprehension:

from boto.ec2 import connect_to_region
conn = connect_to_region('us-east-1')
all_volumes = conn.get_all_volumes()
instance_volumes = [v for v in all_volumes if v.attach_data.instance_id = "<instanceID>"]

This works, and works well enough for my purposes. All the same, I'm curious if there's a way to use get_all_volumes()'s built-in filtering to get the same result. For example, if I were searching for instances whose "Name" tag match a certain pattern, I could do this:

filters = {'tag:Name': '<name>'}
reservations = self.conn.get_all_instances(filters=filters)
instances = [i for r in reservations for i in r.instances]

get_all_volumes() has a similar filter parameter, but I can't get it to work on boto.ec2.volume.Volume.attach_data.instance_id. Am I missing something obvious or is filtering by instance_id on volumes not possible?

like image 422
Christopher Avatar asked Dec 20 '22 12:12

Christopher


1 Answers

Yes, you can use the server-side filter to limit the results of DescribeVolumes to only volumes that are attached to a particular instance ID.

from boto.ec2 import connect_to_region
conn = connect_to_region('us-east-1')

volumes = conn.get_all_volumes(filters={'attachment.instance-id': 'i-11111111'})

Would limit the volumes to those attached to instance i-11111111. You could also provide a list of instance ID's as the value in the dictionary.

like image 69
garnaat Avatar answered Jan 04 '23 19:01

garnaat