从CloudWatch Event中读取AWS s3存储桶名称

时间:2018-03-26 18:56:41

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

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

以下是我的代码:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')  

def lambda_handler(event, context):

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

1 个答案:

答案 0 :(得分:2)

S3桶级操作的CloudTrail事件的格式与@Woodrow发布的格式不同。实际上,bucket的名称位于名为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)