How to specify different environment variables for each stage type in AWS-SAM template.yml

Viewed 689

I wish to set different environment variables for each build stage in my template.yml

I will imagine something like this:

Globals:
  Function:
    Environment:
      Variables:
        SomeHost: x.amazonaws.com
        DBName: somename
        DBPort: 5430
        DBUsername: ${var1}
        API_BASE_URL: ${var2}

Parameters:
  paramEnvironment:
    Type: String
    AllowedValues:
    - stage
    - prod
    Default: stage

Where I can set

stage:
  var1: user1
  API_BASE_URL: https://baseurl1.com
prod:
  var1: user2
  API_BASE_URL: https://baseurl2.com

 And when I run deploy with paramEnvironment the environment will get all the stage based variables

1 Answers

The ideal way of handling different environments (especially for serverless) is having multiple AWS accounts under the same organization(AWS Organizations) where you have a separate account for staging and another account for production.

So in case if you want to solve this within a single account, you can either use SSM parameter or Mappings in SAM template.

Referencing existing system manager param

Parameters:
  ApiBaseUrl :
    Type : 'AWS::SSM::Parameter::Value<String>'
    Default:  /${paramEnvironment}/apiBaseUrl

By mappings in SAM template

Mappings:
    EnvVariables:
        stage:
           var1: user1
           API_BASE_URL: https://baseurl1.com
        prod:
           var1: user2
           API_BASE_URL: https://baseurl2.com

and refer the map using,

!FindInMap [ EnvVariables, ${paramEnvironment}, API_BASE_URL ] 
Related