【问题标题】:Read AWS s3 Bucket Name from CloudWatch Event从 CloudWatch 事件中读取 AWS s3 存储桶名称
【发布时间】:2018-03-26 18:56:40
【问题描述】:

我正在编写一个 Lambda 函数,该函数在创建新的 s3 存储桶时触发。我有一个触发 lambda 函数的 cloudwatch 函数。我看到将整个事件作为输入传递给 lambda 函数的打开方式。当我这样做时,如何让我的 Lambda 函数从事件中读取存储桶的名称并将名称作为值分配给字符串变量?

我的代码如下所示:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')  

def lambda_handler(event, context):

    bucket = event['s3']['bucket']['name']

【问题讨论】:

  • 嘿@Woodrow,当我尝试 bucket_name = event['Records'][0]['s3']['bucket']['name'] 我得到 File "/var/task/ lambda_function.py",第 12 行,在 lambda_handler bucket_name = event['Records'][0]['s3']['bucket']['name'] KeyError: 'Records'

标签: amazon-web-services amazon-s3 aws-lambda


【解决方案1】:

S3 存储桶级别操作的 CloudTrail 事件的格式与 @Woodrow 发布的格式不同。实际上,存储桶的名称在一个名为requestParameters 的 JSON 对象中。此外,整个事件被封装在Records 数组中。见CloudTrail Log Event Reference

用于创建存储桶的 CloudTrail 事件的截断版本

"eventSource": "s3.amazonaws.com",
"eventName": "CreateBucket",
"userAgent": "signin.amazonaws.com",
"requestParameters": {
    "CreateBucketConfiguration": {
        "LocationConstraint": "aws-region",
        "xmlns": "http://s3.amazonaws.com/doc/2006-03-01/"
    },
    "bucketName": "my-awsome-bucket"
}

因此,您的代码可能类似于:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')  

def lambda_handler(event, context):
    for record in event['Records']:
        if record['eventName'] == "CreateBucket":
            bucket = record['requestParameters']['bucketName']
            print(bucket)

【讨论】:

  • 嗨,我正在使用 CloudWatch 创建存储桶事件触发的 Lambda 函数:触发器如下所示:{ "source": [ "aws.s3" ], "detail-type" : [ "AWS API Call via CloudTrail" ], "detail": { "eventSource": [ "s3.amazonaws.com" ], "eventName": [ "CreateBucket" ] } }
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2021-05-14
  • 1970-01-01
相关资源
最近更新 更多