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

Chr*_*sjx 5 python eventtrigger amazon-web-services aws-lambda

跟进此问题: 筛选 CloudWatch Logs 以提取实例 ID

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

我的目标是:

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

Cloudwatch触发事件是:

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以看到这样的例子:

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)
Run Code Online (Sandbox Code Playgroud)

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

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

我怀疑它是这样的:

myTag = event.details.instance-id.tags["startgroup1"]
Run Code Online (Sandbox Code Playgroud)

Vai*_* PS 0

在事件的详细信息部分,您将获得实例 ID。使用实例 ID 和 AWS 开发工具包,您可以查询标签。以下是示例事件

{
  "version": "0",
  "id": "ee376907-2647-4179-9203-343cfb3017a4",
  "detail-type": "EC2 Instance State-change Notification",
  "source": "aws.ec2",
  "account": "123456789012",
  "time": "2015-11-11T21:30:34Z",
  "region": "us-east-1",
  "resources": [
    "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"
  ],
  "detail": {
    "instance-id": "i-abcd1111",
    "state": "running"
  }
}
Run Code Online (Sandbox Code Playgroud)