3
votes

I create CloudFormation template for my AWS Lambda function and I need to specify different values of environment variables for different lambda aliases. My template looks like:

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"

As you see, I have two aliases - QA and Prod and bunch of environment variables. I specified variables with common values in lambda function declaration. But I need to declare for QA alias env. variable's values related to QA, and for Prod alias - values for Prod environment. Any ideas how can I do that?

1
It's better to create 2 lambda functions for 2 different environment.ittus
@ittus why is it better than using aliases?Gleb
security best practice is to have different accounts for different environments to minimise "blast radius" in case of a security breach. If somebody hacks one of your accounts (i.e environments), then they won't have access to the other ones.Jeshan
@Jeshan Babooa it's a good point, thank you for it!Gleb

1 Answers

1
votes

You can use CloudFormation Parameters to do this. As a quick example:

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

Then, if you want to use a different parameter, when you deploy via CLI, you can override with parameter-overrides like this:

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