Search code examples
pythonaws-lambdaserverless-framework

How to pass stage to handler.py from serverless.yml function in serverless framework


I have some functions configured using the serverless framework yaml file, for this I'm using a --stage flag in the command line script which is then set in the correct place in the serverless file to deploy to the right place.

How can I then find out what stage I'm on in the handler.py file so that I can reference the correct database

I've read these: Check env variables in serverless.yml file (Serverless Framework) https://forum.serverless.com/t/get-stage-from-handler-js/402/3

and tried using event.stage in the handler, which doesn't work offline (haven't tested this deployed)


Solution

  • You can now use the environment key to add environment variables to your function. For example:

    functions:
      hello:
        handler: handler.hello
        environment:
          APP_STAGE: ${sls:stage}
    

    Then you can access it using os.environ in Python:

    import os
    
    def hello(event, context):
       stage = os.environ.get("APP_STAGE")