如何通过使用 boto 传递卷 ID 来查找 ec2 实例 ID



我想将卷 id 作为参数传递,然后在 python 中返回实例 ID

您需要

调用describe_instances()

您可以在 Python 中自己过滤结果,也可以传递 Filters 以获得block-device-mapping.volume-id

import boto3
ec2_client = boto3.client('ec2', region_name='ap-southeast-2')
response = ec2_client.describe_instances(Filters=[{'Name':'block-device-mapping.volume-id','Values':['vol-deadbeef']}])
instance_id = response['Reservations'][0]['Instances'][0]['InstanceId']
print(instance_id)

一个卷一次只能附加到一个实例,因此此代码假定只返回一个实例。

正如@Rajesh所指出的,一种更简单的方法是使用 DescribeVolumes ,它返回Attachment信息:

import boto3
ec2_client = boto3.client('ec2', region_name='ap-southeast-2')
response = ec2_client.describe_volumes(VolumeIds=['vol-deadbeef'])
print(response['Volumes'][0]['Attachments'][0]['InstanceId'])

此代码假定实例是卷上的第一个附件(因为 EBS 卷只能附加到一个实例(。

最新更新