Sunday, November 19, 2017

How to access an AWS Lambda environment variable from Python?

AWS Lambda environment variables can be defined using the AWS Console, CLI, or SDKs. This is how you would define an AWS Lambda that uses an LD_LIBRARY_PATH environment variable using AWS CLI:
aws lambda create-function \
  --region us-east-1
  --function-name myTestFunction
  --zip-file fileb://path/package.zip
  --role role-arn
  --environment Variables={LD_LIBRARY_PATH=/usr/bin/test/lib64}
  --handler index.handler
  --runtime nodejs4.3
  --profile default
Once created, environment variables can be read using the support your language provides for accessing the environment, e.g. using process.env for Node.js. When using Python, you would need to import the os library, like in the following example:
...
import os
...
print("environment variable: " + os.environ['variable'])

Resource Link:



Assuming you have created the .env file along-side your settings module.
.
├── .env
└── settings.py
Add the following code to your settings.py
# settings.py
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
Alternatively, you can use find_dotenv() method that will try to find a .env file by (a) guessing where to start using file or the working directory -- allowing this to work in non-file contexts such as IPython notebooks and the REPL, and then (b) walking up the directory tree looking for the specified file -- called .env by default.
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
Now, you can access the variables either from system environment variable or loaded from .env file.

Resource Link:



A workaround is to use python-dotenv: https://github.com/theskumar/python-dotenv
import os
import dotenv

dotenv.load_dotenv(os.path.join(here, "../.env"))
dotenv.load_dotenv(os.path.join(here, "../../.env"))
It tries to load it twice because when ran locally it's in project/.env and when running un Lambda the .env is located in project/component/.env
Resource Link: https://stackoverflow.com/a/40938309/2293534

No comments:

Post a Comment