如何通过单个serverless.yml部署两个REST类型API Gateway(公/私)?
单个serverless.yml部署两个REST API Gateway(公开+私有)
完全可以通过单个serverless.yml文件完成两个REST类型API Gateway的部署,一个公开、一个私有。核心思路是利用Serverless Framework的resources字段,直接定义两个AWS::ApiGateway::RestApi资源,分别配置公开/私有属性,再关联对应的Lambda函数和API部署规则。
下面是具体的配置示例:
service: dual-api-gateway-example provider: name: aws runtime: nodejs18.x region: us-east-1 # 定义两个Lambda函数,分别对应公开和私有API的处理逻辑 functions: publicApiHandler: handler: handler.publicHandler privateApiHandler: handler: handler.privateHandler resources: Resources: # 公开REST API Gateway PublicRestApi: Type: AWS::ApiGateway::RestApi Properties: Name: PublicRestApi Description: 公开访问的REST API Gateway EndpointConfiguration: Types: - EDGE # 公开网关可选EDGE/REGIONAL类型 # 私有REST API Gateway PrivateRestApi: Type: AWS::ApiGateway::RestApi Properties: Name: PrivateRestApi Description: 仅VPC内访问的私有REST API Gateway EndpointConfiguration: Types: - PRIVATE VPCEndpointIds: - !Ref YourVPCEndpointId # 替换为你的VPC端点ID # 公开API的资源和方法配置 PublicApiResource: Type: AWS::ApiGateway::Resource Properties: ParentId: !GetAtt PublicRestApi.RootResourceId PathPart: public RestApiId: !Ref PublicRestApi PublicApiMethod: Type: AWS::ApiGateway::Method Properties: HttpMethod: GET ResourceId: !Ref PublicApiResource RestApiId: !Ref PublicRestApi AuthorizationType: NONE Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${publicApiHandler.Arn}/invocations # 私有API的资源和方法配置 PrivateApiResource: Type: AWS::ApiGateway::Resource Properties: ParentId: !GetAtt PrivateRestApi.RootResourceId PathPart: private RestApiId: !Ref PrivateRestApi PrivateApiMethod: Type: AWS::ApiGateway::Method Properties: HttpMethod: GET ResourceId: !Ref PrivateApiResource RestApiId: !Ref PrivateRestApi AuthorizationType: NONE # 可根据需求配置IAM等授权方式 Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${privateApiHandler.Arn}/invocations # 公开API的部署阶段 PublicApiDeployment: Type: AWS::ApiGateway::Deployment DependsOn: PublicApiMethod Properties: RestApiId: !Ref PublicRestApi StageName: prod # 私有API的部署阶段 PrivateApiDeployment: Type: AWS::ApiGateway::Deployment DependsOn: PrivateApiMethod Properties: RestApiId: !Ref PrivateRestApi StageName: prod Outputs: PublicApiUrl: Value: !Sub https://${PublicRestApi}.execute-api.${AWS::Region}.amazonaws.com/prod/public PrivateApiUrl: Value: !Sub https://${PrivateRestApi}.execute-api.${AWS::Region}.amazonaws.com/prod/private
关键配置说明
- 公开网关的
EndpointConfiguration.Types设置为EDGE或REGIONAL,私有网关设置为PRIVATE并关联目标VPC端点。 - 通过
AWS::ApiGateway::Method将每个网关的资源路径关联到对应的Lambda函数,采用AWS_PROXY集成模式实现全代理。 - 需分别定义两个
AWS::ApiGateway::Deployment资源,完成各自网关的部署和阶段配置,确保API可用。
内容的提问来源于stack exchange,提问作者Joey Yi Zhao
相关产品推荐
相关产品推荐

