Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/65917192/how-to-specify-different-environment-variables-for-each-stage-type-in-aws-sam-te

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...