How to set environment variables according to stage in cloud formation template

Viewed 1805

The environment variables in the lambda handler has to be set via lambda handler according to the stage. The values for schema, endpoint are different for different stage. How can this be done via yml template. I am new to this, so don't know how this will be done.

Parameters:
   Stage: {Type: String, Default: ''}
Resources:
   LambdaHandler:
   Type: AWS::Serverless::Function
   Properties:
       Environment:
          Variables:
          ......
          ......

How to continue further?

4 Answers

template.yaml:

Parameters:
  Environment:
    AllowedValues:
      - dev
      - prod
    Type: String

Resources:
  myLambda:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          stage: !Ref Environment

Your shell:

$ aws cloudformation deploy --parameter-overrides Environment=dev

Say you want a variable conditional on the environment:

Parameters:
  Environment:
    AllowedValues:
      - dev
      - prod
    Type: String

Mappings:
  Environments:
    dev:
      LogLevel: "DEBUG"
    prod:
      LogLevel: "ERROR"

Resources:
  myLambda:
    Type: AWS::Lambda::Function
    Properties:
      Environment:
        Variables:
          LOG_LEVEL: !FindInMap [Environments, !Ref Environment, LogLevel]

I presume it would be:

Environment:
        Variables:
          your-key: !Ref Stage

You can use conditions like below

MyNotCondition:
  !Not [!Equals [!Ref EnvironmentType, prod]]
Related