简体   繁体   English

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

[英]Read AWS s3 Bucket Name from CloudWatch Event

I am working on writing a Lambda function that triggers when a new s3 bucket is created. 我正在编写Lambda函数,该函数在创建新的s3存储桶时触发。 I have a cloudwatch function that triggers the lambda function. 我有一个可触发lambda函数的cloudwatch函数。 I see the open to pass the whole event to the lambda function as input. 我看到将整个事件传递给lambda函数作为输入的开放。 When I this, how do I get my Lambda function to read the bucket's name from the event and assign the name as the value to a string variable? 当我这样做时,如何获取Lambda函数以从事件中读取存储桶的名称,并将该名称作为值分配给字符串变量?

Here is what my code looks like: 这是我的代码:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')  

def lambda_handler(event, context):

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

CloudTrail events of S3 bucket level operations have different format than the one posted by @Woodrow. S3存储桶级操作的CloudTrail事件的格式与@Woodrow发布的事件的格式不同。 Actually, the name of bucket is within a JSON object called requestParameters . 实际上,存储桶的名称在一个名为requestParameters的JSON对象中。 Moreover, the whole event is encapsulated within Records array. 而且,整个事件都封装在Records数组中。 See CloudTrail Log Event Reference 请参阅CloudTrail日志事件参考

Truncated version of CloudTrail event for bucket creation 用于创建存储桶的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"
}

Therefore, your code could look something like: 因此,您的代码可能类似于:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM