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

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?



Solution 1:[1]

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]

Solution 2:[2]

I presume it would be:

Environment:
        Variables:
          your-key: !Ref Stage

Solution 3:[3]

You can use conditions like below

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

Solution 4:[4]

Have a look at this article on how to use stage parameters and use mappings to setup environment variables https://www.singlestoneconsulting.com/blog/cloudformation-mapping-and-conditionals-making-your-templates-more-universal/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 John Rotenstein
Solution 3 samtoddler
Solution 4 coolxeo