如何在 CloudFormation 模板中设置 Lambda 并发限制

How to set Lambda concurrency limit in CloudFormation template

我想通过 cloudformation 配置文件同时限制 运行 lambda 的数量。我试图寻找它,但没有运气。在 documentation page 上没有关于它的信息。 设置此限制的方法有:通过控制台或通过 API。但是如何在堆栈部署时自动执行此操作?

我猜,由于此功能相对较新(并且文档中没有任何线索),因此无法在 cloudformation 模板中开箱即用。如果您想使用 CF,最好的选择是 Custom Resource,您可以在其中通过 lambda 使用例如boto3 的 put_function_concurrency 方法。

自定义资源上的一些资源: - 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

根据@DrEigelb 的建议,我创建了 custom resource which does that:

# 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):
              try:
                  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:
  LambdaConfiguratorFunctionArnOutput:
    Value: !GetAtt LambdaConfiguratorFunction.Arn
    Export:
      Name: Custom--LambdaConfiguratorFunction--Arn

您现在可以使用

设置每函数并发
ReservedConcurrentExecutions

此 属性 允许您为每个 Lambda 函数设置并发限制。

Documentation for this property.