在CloudFormation模板中为不同的AWS Lambda别名配置环境变量

时间:2018-05-18 14:25:36

标签: amazon-web-services aws-lambda yaml amazon-cloudformation

我为AWS Lambda函数创建了CloudFormation模板,我需要为不同的lambda别名指定不同的环境变量值。 我的模板看起来像:

AWSTemplateFormatVersion: "2010-09-09"

Transform: "AWS::Serverless-2016-10-31"

Description: Lambda function configuration

Resources:
  EndpointLambda:
    Type: "AWS::Lambda::Function"
    Properties:
      FunctionName: "endpoint-lambda"
      Handler: "com.test.aws.RequestHandler::handleRequest"
      Runtime: java8
      Code:
        S3Bucket: "lambda-functions"
        S3Key: "test-endpoint-lambda-0.0.1.jar"
      Description: Test Lambda function
      MemorySize: 256
      Timeout: 60
      Environment:
        Variables:
          ES_HOST: test-es-host-url
          ES_ON: true
          ES_PORT: 443
          ES_PROTOCOL: https
          REDIS_URL: test-redis-host-url

  QaLambdaAlias:
    Type: "AWS::Lambda::Alias"
    Properties:
      FunctionName: !Ref EndpointLambda
      FunctionVersion: 1
      Name: "QA"
      Description: "QA alias"

  ProdLambdaAlias:
    Type: "AWS::Lambda::Alias"
    Properties:
      FunctionName: !Ref EndpointLambda
      FunctionVersion: 1
      Name: "Prod"
      Description: "Production alias"

如你所见,我有两个别名 - QA和Prod以及一堆环境变量。我在lambda函数声明中指定了具有公共值的变量。但我需要声明QA别名env。与QA相关的变量值,以及Prod别名 - Prod环境的值。任何想法我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用CloudFormation Parameters执行此操作。作为一个简单的例子:

Parameters:
  LambdaRuntime:
    Type: String
    Default: 'java8'
    Description: What Lambda runtime do we use?

Resources:
  QaLambdaAlias:
    Type: "AWS::Lambda::Alias"
    Properties:
      FunctionName:
        Ref: EndpointLambda
      FunctionVersion: 1
      Name: "QA"
      Description: "QA alias"
      Runtime:
        Ref: LambdaRuntime

然后,如果您想使用其他参数,当您通过CLI进行部署时,可以使用parameter-overrides覆盖,如下所示:

aws cloudformation deploy --stack-name MyStack --template-file \
CloudFormation/MyStack.yaml --capabilities CAPABILITY_IAM \
--parameter-overrides LambdaRuntime=nodejs8.10