我想通过 cloudformation 配置文件来限制同时运行的 lambdas 的数量。我试着搜索了一下,但没有成功。在 文档页面 上没有这方面的信息。 有几种方法可以设置这个限制:通过控制台或通过API。但我如何才能在堆栈部署时自动做到这一点?
你现在可以通过以下方式设置每个函数的并发性
ReservedConcurrentExecutions
该属性允许你为你的每个Lambda函数设置一个并发限制。
但这不是与限制不同吗?
DrEigelb
发布于
2018-01-12
0
人赞同
我猜测,由于这个功能相对较新(而且文档中没有任何线索),所以没有办法在云计算模板中做到开箱即用。如果你想使用CF,你最好的选择是
自定义资源
,通过使用boto3的
put_function_concurrency
方法的lambda设置并发性。
一些关于自定义资源的资源。
-
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html
-
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-custom-resources-lambda-lookup-amiids.html
-
http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html
谢谢你的建议。我将尝试实施它。
German Lashevich
发布于
2018-01-12
0
人赞同
根据@DrEigelb的建议,我创建了
自定义资源,可以做到这一点
。
# This stack contains basic components for custom resource which allows you to
# configure lambda concurrency limit during stack creation. It contains lambda
# function and a role for the lambda. To start you should deploy this stack to
# the region and the account where you want to use it, then add custom resource
# with two parameters (`LambdaArn` and `ReservedConcurrentExecutions`) into you
# stack:
# LambdaConfigurator:
# Type: Custom::LambdaConfigurator
# Properties:
# ServiceToken: !ImportValue Custom--LambdaConfiguratorFunction--Arn
# Region: !Ref "AWS::Region"
# LambdaArn: !GetAtt TargetLambda.Arn
# ReservedConcurrentExecutions: 10
Description: Holds custom resource for changing configuration of lambda
AWSTemplateFormatVersion: '2010-09-09'
Resources:
LambdaConfiguratorFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import re
import boto3
import cfnresponse
def handler(event, context):
if event['RequestType'] == 'Delete':
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
return
function_name = event['ResourceProperties']['LambdaArn']
concurrency = int(event['ResourceProperties']['ReservedConcurrentExecutions'])
print('FunctionName: {}, ReservedConcurrentExecutions: {}'.format(function_name, concurrency))
client = boto3.client('lambda')
client.put_function_concurrency(FunctionName=function_name, ReservedConcurrentExecutions=concurrency)
cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
except Exception as e:
err = '{}: {}'.format(e.__class__.__name__, str(e))
print(err)
cfnresponse.send(event, context, cfnresponse.FAILED, {'Reason': err})
Handler: index.handler
Runtime: python3.6
Timeout: 30
Role:
Fn::GetAtt: LambdaConfiguratorLambdaExecutionRole.Arn
LambdaConfiguratorLambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- lambda:*
Resource: "*"
Outputs: