使用无服务器有条件地设置 lambda 的预置并发

Sid*_*kar 5 amazon-web-services aws-lambda serverless-framework serverless

lambda 函数是使用 serverless(2.22) 创建的,并使用 codebuild (standard5.0) 进行部署。我想有条件地仅为 UAT 和 Prod env 设置预置并发,而不是为 dev 和 test env 设置预置并发。

这些是我尝试过的事情:

无服务器.yml:

    ...
    alarms:
      - functionErrors
    Conditions:
      isProdOrUAT: {"Fn::Or": [{"${opt:stage}": "prod"}, {"${opt:stage}": "uat"}]} 
functions:
  TestApi:
    handler: test.api.StreamLambdaHandler::handleRequest
    description: Lambda function for the Test API
    timeout: 20
    custom: !If [isProdOrUAT, "${file(./provisionedconcurrency.yml)}", !Ref "AWS::NoValue"]
Run Code Online (Sandbox Code Playgroud)

配置并发.yml

provisionedConcurrency: "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,会成功导入文件,构建也通过。但 UAT 和 Prod 的 lambda 配置中没有附加预配置并发。

无服务器.yml

provisionedConcurrency: "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}"
Run Code Online (Sandbox Code Playgroud)

在这种情况下出现以下错误

Error --------------------------------------------------
  Error: The CloudFormation template is invalid: [/Resources/TestApiProvConcLambdaAlias/Type/ProvisionedConcurrencyConfig/ProvisionedConcurrentExecutions] 'null' values are not allowed in templates 
Run Code Online (Sandbox Code Playgroud)

检查了一下serverless-state.json,发现有这个。

 ...
    alarms:
      - functionErrors
    Conditions:
      isProdOrUAT: {"Fn::Or": [{"${opt:stage}": "prod"}, {"${opt:stage}": "uat"}]} 
functions:
  TestApi:
    handler: test.api.StreamLambdaHandler::handleRequest
    description: Lambda function for the Test API
    timeout: 20
    provisionedConcurrency: !If [isProdOrUAT, "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}", !Ref "AWS::NoValue"]
Run Code Online (Sandbox Code Playgroud)

elb*_*bik 1

只是尽量保持简单,没有额外的 yml 配置和复杂的 if 语句,并利用条件变量

custom:
    provisionedConcurrency:
        prod: 5
        uat: 5
        default: 0
        
functions:    
    TestApi:
        handler: test.api.StreamLambdaHandler::handleRequest
        description: Lambda function for the Test API
        timeout: 20
        provisionedConcurrency: ${self:custom.provisionedConcurrency.${self:provider.stage}, self:custom.provisionedConcurrency.default}
Run Code Online (Sandbox Code Playgroud)

  • 赞成,但是:serverless 2.x 不喜欢配置并发数为 0,并且会发出配置警告和弃用警告: - `Serverless: Configuration warning: Serverless: at 'functions.testapi.provisionedConcurrency': should be >= 1` - `无服务器:弃用警告:从下一个主要版本开始,无服务器将默认抛出配置错误。现在通过在服务配置中添加“configValidationMode: error”来适应此行为更多信息:https://www.serverless.com/framework/docs/deprecations/#CONFIG_VALIDATION_MODE_DEFAULT` (3认同)