gpt4 book ai didi

python - 如何在AWS Lambda中使用python访问事件对象?

转载 作者:行者123 更新时间:2023-12-02 09:22:32 26 4
gpt4 key购买 nike

要跟进这个问题: Filter CloudWatch Logs to extract Instance ID

我认为这使得问题不完整,因为它没有说明如何使用 python 访问事件对象。

我的目标是:

  • 读取由运行状态更改触发的实例
  • 获取与实例关联的标签值
  • 启动具有相同标签的所有其他实例

Cloudwatch 触发事件是:

{
"source": [
"aws.ec2"
],
"detail-type": [
"EC2 Instance State-change Notification"
],
"detail": {
"state": [
"running"
]
}
}

我可以看到这样的例子:

def lambda_handler(event, context):

# here I want to get the instance tag value
# and set the tag filter based on the instance that
# triggered the event

filters = [{
'Name': 'tag:StartGroup',
'Values': ['startgroup1']
},
{
'Name': 'instance-state-name',
'Values': ['running']
}
]

instances = ec2.instances.filter(Filters=filters)

我可以看到事件对象,但我不知道如何深入了解其状态更改为正在运行的实例的标签。

请问,我可以通过什么对象属性从触发的实例中获取标签?

我怀疑它是这样的:

myTag = event.details.instance-id.tags["startgroup1"]

最佳答案

传递给 Lambda 的事件数据包含实例 ID。

然后您需要调用describe_tags()来检索标签的字典。

import boto3
client = boto3.client('ec2')

client.describe_tags(Filters=[
{
'Name': 'resource-id',
'Values': [
event['detail']['instance-id']
]
}
]
)

关于python - 如何在AWS Lambda中使用python访问事件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com