I have some constants that in the handler.js file that needs to be configured different dependent on environment (dev, test, prod). For parameters in serverless.yml it is great that the syntax ${opt:region, ‘eu-west-1’} can be used. But what is best practice for variables inside handler.js file?
Feed it to lambda functions, notice the environment variables I set for that lambda function:
custom: ${file(${opt:stage, self:provider.stage}.yml)}
functions:
createTodos:
handler: handler.create
environment:
environment: ${self:custom.environment}
events:
- http:
path: todos
method: post
cors: true
Then you should be fine to reference this variable by below way in handler.js:
const Environment = process.env.environment
So you can control to use which environment file by feeding option --stage when deploy
# use the default stage, which is dev, so serverless will pick up the variables from file `dev.yml`
sls deploy
# feed with option --stage, so serverless will pick up the variables from file `prod.yml`
sls deploy --stage prod