使用Serverless Framework配置双AWS Lambda通过EventBridge收发事件问题
问题修复方案
以下是你配置中遗漏的问题和对应解决方法:
事件总线名称拼写错误
你的YAML配置中引用的事件总线名称为vehicle-bus,但vehicle函数代码中写的是拼写错误的veihcle-bus,导致事件发送到不存在的总线,无法触发下游函数,修正代码中的总线名称即可。缺少Lambda访问EventBridge的权限
你需要在serverless.yml的provider块下添加IAM权限配置,给vehicle函数授予发送事件到EventBridge的权限,示例配置:
provider: name: aws runtime: nodejs18.x # 建议替换已停止官方支持的nodejs12.x lambdaHashingVersion: '20201221' iam: role: statements: - Effect: Allow Action: events:PutEvents Resource: arn:aws:events:us-east-1:${aws:accountId}:event-bus/vehicle-bus
- 未提前创建自定义事件总线
Serverless Framework的EventBridge触发器默认不会自动创建你指定的自定义事件总线vehicle-bus,你可以选择两种方式解决:
- 直接在AWS EventBridge控制台手动创建名称为
vehicle-bus的自定义总线 - 在
serverless.yml的resources块中添加CloudFormation配置自动创建总线,示例:
resources: Resources: VehicleEventBus: Type: AWS::Events::EventBus Properties: Name: vehicle-bus
- 同个Lambda适配双触发源的逻辑优化
上述基础问题排查完成后,你可以在bundle函数中增加触发源判断,不同触发源返回对应格式的结果,示例逻辑:
module.exports.bundle = async (event) => { // 判断是否为EventBridge触发 if (event.source && event['detail-type']) { // EventBridge触发场景,处理业务逻辑后可返回任意格式结果 console.log('收到EventBridge事件:', event) return { result: 'success' } } // HTTP触发场景返回标准HTTP格式响应 return { statusCode: 200, body: JSON.stringify( { message: "BUNDLE", input: event, aos: "First test OK", }, null, 2 ), }; };
内容的提问来源于stack exchange,提问作者davbryn
相关产品推荐
相关产品推荐

