jbflow
jbflow

Reputation: 642

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)

Upvotes: 1

Views: 946

Answers (2)

D Malan
D Malan

Reputation: 11484

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")

Upvotes: 1

Maks Babarowski
Maks Babarowski

Reputation: 672

You can try interpolating stage name with the function name, like this:

functions:
  myFunction:
    handler: my_file.my_function
    name: ${sls:stage}-my-function

The function name can be obtained by handler code from a context parameter, property function_name.

If you use the convention mentioned above, you can obtain stage name in this way:

def my_function(event, context):
   stage = context['function_name'].split('-')[0]

Upvotes: 2

Related Questions