在一个无服务器应用程序模型中部署多个lambdas

时间:2018-01-17 14:11:25

标签: java amazon-web-services aws-lambda aws-api-gateway

我想使用无服务器应用程序模型(sam.yml)文件来部署两个带有api网关集成的AWS lambda函数。我的文件看起来像这样:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: "Client Service"
Resources:
  PetStoreServerFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: server.LambdaHandler::handleRequest
      Runtime: java8
      CodeUri: petstore-server/target/petstore-server-1.0-SNAPSHOT.jar
      MemorySize: 512
      Policies:
        - AWSLambdaBasicExecutionRole
      Timeout: 20
      Events:
        GetResource:
          Type: Api
          Properties:
            Path: /server/{proxy+}
            Method: any
  PetStoreClientFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: client.LambdaHandler::handleRequest
      Runtime: java8
      CodeUri: petstore-client/target/petstore-client-1.0-SNAPSHOT.jar
      MemorySize: 512
      Policies:
        - AWSLambdaBasicExecutionRole
      Timeout: 20
      Events:
        GetResource:
          Type: Api
          Properties:
            Path: /client/{proxy+}
            Method: any

在lambda Web控制台中,我可以看到两个函数都已创建,但我只能通过API网关调用其中一个函数。对于另一个,我得到{"message":"Gateway timeout"}

有什么想法吗?在单个无服务器应用程序模型中描述两个功能部署的最佳方法是什么?

我见过这个例子:https://github.com/awslabs/serverless-application-model/blob/master/examples/2016-10-31/api_backend/template.yaml

然而,这会从相同的源代码创建两个lambda函数。这不是我想要实现的目标。我想在单个 sam.yml文件中的不同部署中创建两个lambda函数。

1 个答案:

答案 0 :(得分:0)

我找到了答案 here。您需要先设置ApiGatewayApi资源,然后使用ProxyApiRoot更新Events并引用ApiGatewayApi

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: /lambda1
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ProxyApiRoot:
          Type: Api
          Properties:
            RestApiId: !Ref ApiGatewayApi
            Path: /lambda1
            Method: ANY
  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: /lambda2
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ProxyApiRoot:
          Type: Api
          Properties:
            RestApiId: !Ref ApiGatewayApi
            Path: /lambda2
            Method: ANY
  LambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: /lambda3
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ProxyApiRoot:
          Type: Api
          Properties:
            RestApiId: !Ref ApiGatewayApi
            Path: /lambda3
            Method: ANY