1 回答
TA贡献1863条经验 获得超2个赞
“我想获取任何给定 EC2 实例的 EBS 卷及其大小的列表。”
这是使用该resource方法的代码:
import boto3
ec2_resource = boto3.resource('ec2')
for instance in ec2_resource.instances.all():
for volume in instance.volumes.all():
print(instance.id, volume.id, volume.volume_type, volume.size)
并使用client方法:
import boto3
ec2_client = boto3.client('ec2')
response = ec2_client.describe_instances()
for reservation in response['Reservations']:
for instance in reservation['Instances']:
volumes = ec2_client.describe_volumes(
Filters=[{'Name':'attachment.instance-id','Values':[instance['InstanceId']]}]
)
for disk in volumes['Volumes']:
print(instance['InstanceId'], disk['VolumeId'], disk['VolumeType'], disk['Size'])
但是,这会导致多次 API 调用(每个实例DescribeInstances()一次调用)。DescribeVolumes()
此版本仅使用一次调用DescribeVolumes()并按 InstanceId 排序:
import boto3
ec2_resource = boto3.resource('ec2')
volumes = [(v.attachments[0]['InstanceId'], v.id, v.size)
for v in ec2_resource.volumes.filter(Filters=[{'Name':'attachment.status','Values':['attached']}])]
for volume in sorted(volumes):
print(volume[0], volume[1], volume[2])
下面是使用该方法的等效代码client:
import boto3
ec2_client = boto3.client('ec2')
response = ec2_client.describe_volumes(Filters=[{'Name':'attachment.status','Values':['attached']}])
volumes = [(v['Attachments'][0]['InstanceId'], v['VolumeId'], v['Size']) for v in response['Volumes']]
for volume in sorted(volumes):
print(volume[0], volume[1], volume[2])
除了根据本网站服务条款授予的许可之外,本文的内容还根据 MIT-0 获得许可。
添加回答
举报