DEV Community

Ken Choong
Ken Choong

Posted on • Edited on

How to set environment variable for Lambda using CDK

In the previous post, I show how to make a Lambda function using CDK. In this post, I will show we can set the environment variable, so we can use it inside the Lambda function.

When to use environment variable?
You want to access different value of a variable depending on production or development environment, but this value is very important, you need to keep it secret, not comfortable to keep it in version control(eg. github).

Some example use case:

  • Access different database depending on production environment
  • Access different Stripe credential depending on environment.

Steps:
In this example, we access different database URL depending on environment.

Use back the previos Lambda function



my_first_lambda_function=PythonFunction(
    self, 'MyFirstLambda',
    entry='lambda/MyFirstLambdaFunction',
    index='app.py',
    runtime=lambda_.Runtime.PYTHON_3_8,
    layers=[boto3_lambda_layer],
    environment={ # ADD THIS, FILL IT FOR ACTUAL VALUE 
        "production_db_url": "YOUR_ACTUAL_PROD_DB_URL",
        "development_db_url": "YOUR_ACTUAL_DEV_DB_URL"
    },
    handler='MyFirstLambdaHandler',
    timeout=core.Duration.seconds(10)
)


Enter fullscreen mode Exit fullscreen mode

Now, we already define the environment variable, now we need to access this inside our Lambda function.



import boto3
import os

def MyFirstLambdaHandler(event, context):
    client = boto3.client('dynamodb')

    # You get the value back like this
    prod = os.environ['production_db_url']
    dev = os.environ['development_db_url']

    # later you other stuff using the above value


Enter fullscreen mode Exit fullscreen mode

Ok, for now you know how to define the environment variable and use it inside the Lambda function. You can put in any value inside environment, in key value depending on you need.

May be you not sure why you need to set environment variable for now, but is ok, next part of the series, you will connecting the dots.

In next part of the series:
We will talk about version, alias for the Lambda function, APIgateway with stageVariables, and use different environment value depending on the Lambda alias

Before you go, if you like this series or find this useful consider to buy me a coffee 😊🤞 for 5 USD or more.
I will prepare a GitHub repo for this whole tutorial series and arrange into separate commit for each part.
This will only available for my supporter cause I spent a lot of time to prepare this. Anyway, I appreciate you here. Have a good day.


bmaco

Shout out to me on Twitter: @upupkenchoong

Top comments (0)