I am trying to get a list of EBS volumes in EC2 using python.
Here is my code:
import boto3
import objectpath
aws_account = 'company-lab'
region = 'us-east-1'
session = boto3.Session(profile_name=aws_account, region_name=region)
ec2 = session.client("ec2")
instance_list = ec2.describe_instances()
for reservation in instance_list["Reservations"]:
for instance in reservation.get("Instances", []):
tree = objectpath.Tree(instance)
block_devices = set(tree.execute('$..BlockDeviceMappings[\'Ebs\'][\'VolumeId\']'))
block_devices = list(block_devices)
for volume_id in block_devices:
volume = ec2.Volume(volume_id)
When I try that I get back the following error:
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\site-packages\botocore\client.py", line 573, in __getattr__
raise AttributeError(
AttributeError: 'EC2' object has no attribute 'Volume'
I am trying to use the boto3 EC2 Volume attribute. I would like to get a list of EBS volumes and their sizes for any given EC2 instance. How can I do that?
"I would like to get a list of EBS volumes and their sizes for any given EC2 instance."
Here is code using the
resource
method:And using the
client
method:However, this results in multiple API calls (one
DescribeInstances()
and then oneDescribeVolumes()
for each instance).This version just uses a single call to
DescribeVolumes()
and sorts by InstanceId:Here is the equivalent code using the
client
method:In addition to the license granted under the terms of service of this site the contents of this post are licensed under MIT-0.