如何在Serverless Compose服务中为各Lambda指定不同共享API网关
为Serverless Framework Compose项目的Lambda指定对应API网关的实现方案
核心思路
利用Serverless Framework Compose的跨服务输出引用能力,让业务服务直接复用infra中创建的公网/私网API网关,分别为两个Lambda配置对应网关的触发器。
步骤1:在infra服务中定义并输出两个API网关
在services/infra/serverless.yml中创建公网和私网API网关,并将它们的ID导出为跨服务可引用的输出:
service: infra provider: name: aws resources: Resources: # 公网API网关 PublicApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: Medical-Public-API EndpointConfiguration: Types: [EDGE] # 默认公网边缘节点 # 私网API网关 PrivateApiGateway: Type: AWS::ApiGateway::RestApi Properties: Name: Medical-Private-API EndpointConfiguration: Types: [PRIVATE] VpcEndpointIds: ["${param:vpcEndpointId}"] # 替换为你的VPC端点ID,需预先创建 outputs: publicApiGatewayId: Value: !Ref PublicApiGateway privateApiGatewayId: Value: !Ref PrivateApiGateway
步骤2:在业务服务中为Lambda指定对应网关的触发器
以service-a为例,在services/service-a/serverless.yml中,为两个Lambda分别配置公网/私网网关的HTTP触发器,通过compose:infra.outputs引用网关ID:
service: service-a provider: name: aws runtime: nodejs18.x # 根据你的运行环境调整 functions: # 公网创建对象的Lambda,关联公网API网关 createObject: handler: src/create.handler events: - httpApi: path: /objects method: post apiId: ${compose:infra.outputs.publicApiGatewayId} # 指定复用公网网关 # 内网管理员审批的Lambda,关联私网API网关 approveObject: handler: src/approve.handler events: - httpApi: path: /admin/objects/{id}/approve method: post apiId: ${compose:infra.outputs.privateApiGatewayId} # 指定复用私网网关 # 可选:添加IAM授权,确保仅管理员角色可调用 authorizer: type: aws_iam
service-b的配置逻辑与service-a完全一致,只需替换函数名称和处理路径即可。
关键注意事项
- 部署顺序:Serverless Compose会自动识别服务依赖,但手动部署时需先部署infra:
serverless deploy --compose infra,再部署业务服务 - 私网网关访问控制:确保VPC端点仅关联允许的内网VPC,同时配合IAM权限或其他授权机制,符合医疗项目的合规要求
- API类型适配:如果使用传统REST API而非HTTP API,将触发器类型改为
http,apiId的引用方式保持不变
内容的提问来源于stack exchange,提问作者Maxence Guyonvarho
相关产品推荐
相关产品推荐

