Get volume information associated with Instance

258 Views Asked by At

I'm trying to retrieve all the volumes associated with an instance.

if volume.attachment_state() == 'attached':

        volumesinstance = ec2_connection.get_all_instances()

        ids = [z for k in volumesinstance for z in k.instances]

        for s in ids:

            try:
                tags = s.tags
                instance_name = tags["Name"]
                print (instance_name)
            except Exception as e:
                print e

However, it's not working as intended.

1

There are 1 best solutions below

0
On BEST ANSWER

You can add filters in get_all_instances method

like this:

filter = {'block-device-mapping.volume-id': volume.id}
        volumesinstance = ec2_connection.get_all_instances(filters=filter)

ids = [z for k in volumesinstance for z in k.instances]

for s in ids:

   try:
       tags = s.tags
       instance_name = tags["Name"]
       print (instance_name)
   except Exception as e:
       print e