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

Serverless Framework 配置同CloudFormation栈S3桶触发Lambda问题

正确配置方案

1. 补全带CORS配置的S3桶定义

你可以直接在现有S3资源属性中补充CorsConfiguration字段完成CORS配置,示例如下:

resources:
  Resources:
    myBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: my-unique-bucket-123 # 需替换为全局唯一的自定义桶名
        CorsConfiguration:
          CorsRules:
            - AllowedHeaders:
                - "*"
              AllowedMethods:
                - GET
                - PUT
                - POST
                - DELETE
              AllowedOrigins:
                - "*" # 生产环境请替换为实际业务域名,避免安全风险
              MaxAge: 3000

2. 修正Lambda事件配置

你原有配置的缩进错误是导致不生效的核心原因,同栈内创建的S3桶不需要加existing: true,直接引用S3资源的逻辑ID即可,正确配置如下:

functions:
  yourLambdaFunc: # 替换为你的Lambda函数名称
    handler: src/index.handler # 替换为你的实际代码执行入口
    events:
      - s3:
          bucket: myBucket # 直接填写上方S3资源的逻辑ID即可
          event: s3:ObjectCreated:Put
          rules:
            - prefix: uploads/

3. 可选:配置Lambda访问S3的权限

如果你的Lambda逻辑需要读取上传的S3对象,需要补充对应的IAM执行权限:

provider:
  name: aws
  runtime: nodejs18.x # 替换为你实际使用的运行时版本
  iamRoleStatements:
    - Effect: Allow
      Action: s3:GetObject
      Resource: arn:aws:s3:::${self:resources.Resources.myBucket.Properties.BucketName}/uploads/*

这套配置所有资源都在同一CloudFormation栈内创建,不会生成额外的辅助对象,仅当对象上传到uploads/路径时才会触发Lambda执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:04