-1

I have bunch of 100 AWS volume id's in a text file. I want pull those volume id's from text file and get it's attached ec2 instance id and instance name. Can some one please help with python boto3 code?

Gax
  • 1
  • did you tried to write a script? is there any error? – Jatin Mehrotra Oct 17 '22 at 03:16
  • I was able to script half way and unable to proceed further. Here is the script I wrote. This basically pulls the volumes in file to a list. import boto3 volumeList = open("volumes.txt", "r") for i in volumeList: print(i) – Gax Oct 17 '22 at 03:20
  • 2
    Look in the docs for [boto3 ec2 volumes](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#volume). After calling `ec2.Volume('id')`, look at the `attachments` attribute. – craigb Oct 17 '22 at 03:36
  • can you please let me know the attachment sample statement? I am bit confused using the attachments. – Gax Oct 17 '22 at 06:05
  • Please provide enough code so others can better understand or reproduce the problem. – user11717481 Oct 17 '22 at 16:11

1 Answers1

1

Here is some code that retrieves the Amazon EC2 Instance ID attached to an Amazon EBS volume:

import boto3

ID = 'vol-08d12e3f3c98c5d17'

ec2_resource = boto3.resource('ec2')

volume = ec2_resource.Volume(ID)

for attachment in volume.attachments:
    print(attachment['InstanceId'])

Note that an Amazon EBS volume can be attached to multiple instances, which is why the code iterates through the attachments list.

If you want to obtain the 'name' of an Amazon EC2 instance, you would need to call DescribeInstances or using Instance('id'). Then, look at the Value associated with the Name tag.

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470