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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With