lambda函数是使用serverless(2.22)创建的,并使用codebuild (standard5.0)部署。我想有条件地仅为UAT和Prod环境设置预置的并发性,而不为开发和测试环境设置。
这些是我尝试过的事情:
serverless.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"]
provisionedconcurrency.yml
provisionedConcurrency: "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}"
在这种情况下,它成功导入了文件,构建也通过了。但是,在UAT和Prod的lambda配置中没有附加已配置的并发性。
serverless.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
provisionedConcurrency: !If [isProdOrUAT, "${ssm:/${opt:stage}/TestsServiceProvisionedConcurrency}", !Ref "AWS::NoValue"]
在这种情况下,得到以下错误
Error --------------------------------------------------
Error: The CloudFormation template is invalid: [/Resources/TestApiProvConcLambdaAlias/Type/ProvisionedConcurrencyConfig/ProvisionedConcurrentExecutions] 'null' values are not allowed in templates
检查serverless-state.json
,发现这个在那里。
"Name": "provisioned",
"ProvisionedConcurrencyConfig": {
"ProvisionedConcurrentExecutions": null
}
Sls大约在一年前添加了剥离空属性的支持,所以现在它非常简单:
custom:
stages:
dev:
# no need to set value for provisionedConcurrency
uat:
provisionedConcurrency: 5
prod:
provisionedConcurrency: 5
functions:
TestApi:
handler: test.api.StreamLambdaHandler::handleRequest
description: Lambda function for the Test API
timeout: 20
provisionedConcurrency: ${self:custom.stages.${self:provider.stage}.provisionedConcurrency, null}
尽量保持简单,不需要额外的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}
我也有同样的问题。现在您可以这样做(YAML示例)
Parameters:
ProvisionedConcurrentExecutions:
Description: The amount of provisioned concurrency to allocate for the function, use 0 to ignore setting
Type: Number
MinValue: 0
MaxValue: 10
Default: 0
Conditions:
UseProvisionedConcurrentExecutions: !Not [!Equals [!Ref ProvisionedConcurrentExecutions, 0]]
Resources:
LambdaFunction:
Type: AWS::Serverless::Function
Properties:
ProvisionedConcurrencyConfig: !If
- UseProvisionedConcurrentExecutions
- ProvisionedConcurrentExecutions: !Ref ProvisionedConcurrentExecutions
- !Ref 'AWS::NoValue'here