0

What is the best practice in regards to env variable with serverless framework.

Ive heard some discussion on the python dotenv environment, but Im not too experience with python so looking for guidance on setting this up and using (an example would be good!)

For example, I want to have an environment variable for db_arn in my serverless handler function.

db_arn = "ec2-xx-xx-xx-xxx.eu-west-1.compute.amazonaws.com"

def getCustomer(): #connect using db_arn

Id like db_arn to be an environment variable (dev, test, prod for example), rather then the hard coded string.

How can this be done with dotenv and how would you organise the serverless service to enable this?

Help much welcome thanks!

Kurt Maile
  • 1,171
  • 3
  • 13
  • 29

1 Answers1

-1

You can use the serverless-plugin-write-env-vars plugin to define environment variables in serverless.yml, like this:

service: my-service

custom:
   writeEnvVars:
      DB_ARN: "ec2-xx-xx-xx-xxx.eu-west-1.compute.amazonaws.com"

plugins:
   - serverless-plugin-write-env-vars

Notice the variables must be defined under custom: and writeEnvVars:.

The plugin will create a .env file during the code deployment to AWS Lambda.

In the code, using python-dotenv you can read the environment variables by loading the .env file:

import os.path
from dotenv import load_dotenv

dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)

db_arn = os.environ.get('DB_ARN')

Just in case, if you need help with deploying and loading external dependencies, look at https://stackoverflow.com/a/39791686/1111215

Community
  • 1
  • 1
Benny Bauer
  • 1,035
  • 1
  • 6
  • 19