Serverless Framework v1.0.0 GA - Environment variables within Python Handlers
<p>What is the best practice in regards to env variable with serverless framework.  </p>

<p>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!)</p>

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

<p>db_arn = "ec2-xx-xx-xx-xxx.eu-west-1.compute.amazonaws.com"</p>

<p>def getCustomer():
   #connect using db_arn</p>

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

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

<p>Help much welcome thanks!</p>

<p>You can use the <a href="https://www.npmjs.com/package/serverless-plugin-write-env-vars" rel="nofollow">serverless-plugin-write-env-vars</a> plugin to define environment variables in <code>serverless.yml</code>, like this:</p>

<pre><code>service: my-service

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

plugins:
   - serverless-plugin-write-env-vars
</code></pre>

<p>Notice the variables must be defined under <code>custom:</code> and <code>writeEnvVars:</code>.</p>

<p>The plugin will create a <code>.env</code> file during the code deployment to AWS Lambda. </p>

<p>In the code, using <a href="https://github.com/theskumar/python-dotenv" rel="nofollow">python-dotenv</a> you can read the environment variables by loading the <code>.env</code> file:</p>

<pre><code>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')
</code></pre>

<p>Just in case, if you need help with deploying and loading external dependencies, look at <a href="http://stackoverflow.com/a/39791686/1111215">http://stackoverflow.com/a/39791686/1111215</a></p>

python aws-lambda serverless-framework