You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Lambda函数中从CloudWatch Event读取S3 Bucket名称

从CloudWatch Event触发的Lambda中提取S3 Bucket名称

嗨,这事儿不难,我来给你捋清楚!当CloudWatch Events(现在也叫EventBridge)触发Lambda时,创建S3 Bucket的事件会包含你需要的Bucket名称,咱们直接从事件对象里提取就行。

第一步:明确事件结构

首先,S3 Bucket创建的CloudWatch Event事件结构大概长这样(简化版):

{
  "detail-type": "AWS API Call via CloudTrail",
  "detail": {
    "eventSource": "s3.amazonaws.com",
    "eventName": "CreateBucket",
    "requestParameters": {
      "bucketName": "your-new-bucket-name"
    }
  }
}

你要的Bucket名就在detail -> requestParameters -> bucketName这个路径里。

第二步:修改你的Lambda代码

把你的代码补全,直接从事件参数里提取这个值就行,还可以加个简单的错误处理防止键不存在的情况:

import boto3
from botocore.exceptions import ClientError

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # 提取Bucket名称
    try:
        bucket_name = event['detail']['requestParameters']['bucketName']
        print(f"获取到的Bucket名称:{bucket_name}")
        
        # 这里可以写你后续要执行的逻辑,比如操作这个Bucket
        # 示例:获取Bucket的ACL(仅作演示,需确保Lambda有对应权限)
        try:
            response = s3.get_bucket_acl(Bucket=bucket_name)
            print(f"Bucket ACL信息:{response}")
        except ClientError as e:
            print(f"操作Bucket时出错:{e}")
            
        return {
            'statusCode': 200,
            'body': f"成功获取Bucket名称:{bucket_name}"
        }
    except KeyError as e:
        print(f"事件中未找到预期的字段:{e}")
        return {
            'statusCode': 400,
            'body': "事件格式不正确,无法提取Bucket名称"
        }

小提示

如果不确定事件结构,你可以先在Lambda里加一行print(event),然后触发一次,去CloudWatch日志里看完整的事件内容,确认字段路径是否正确——毕竟有时候不同的事件源格式可能略有差异,但S3的CreateBucket事件基本都是这个路径。

内容的提问来源于stack exchange,提问作者FreakInSwweet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:49:08