如何使用实例 ID 获取 AWS CloudTrail 事件实例名称?



我正在尝试获取CloudTrail事件的实例名称。我正在从事件中提取实例 ID,但事件似乎没有主机名/实例名称。获取实例名称,所以我尝试将 ID 传递给describe_instance或其他函数(我不确定那会是什么(。本质上,我想传递 ID 并从实例标签中获取实例名称。

我尝试使用all_instances但我不确定如何过滤结果以获取我需要的确切实例的名称。这是我到目前为止所拥有的:

inst = ec2.describe_instances(instanceidT)
for tag in inst.tags:
if tag['Key'] == 'Name':
instanceName= tag['Value'][enter image description here][1]
print(instanceName+ "this is what I am looking for")

instanceidT 具有我从云跟踪事件中提取的实例 ID

下面是使用 boto3资源方法检索特定实例的实例标签的示例:

import boto3
instance_id = 'i-abcd1234'
ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')  # Update accordingly
instance = ec2_resource.Instance(instance_id)
for tag in instance.tags:
if tag['Key'] == 'Name':
instanceName= tag['Value']
print(instanceName)

以下是使用客户端方法的相同内容:

import boto3
instance_id = 'i-abcd1234'
ec2_client = boto3.client('ec2', region_name='ap-southeast-2')  # Update accordingly
instances = ec2_client.describe_instances(InstanceIds=[instance_id])
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
for tag in instance['Tags']:
if tag['Key'] == 'Name':
instanceName= tag['Value']
print(instanceName)

最新更新