How to set environment variables in AWS Lambda

Introduction

Environment variables, as the name suggests, are specific to the environment. Variables that you wish to be able to control externally, without having to make edits to your code and redeploy your function, are generally kept as environment variables. Also, variables whose values you do not wish to directly expose in the code (especially when working in a collaborative setting) can also be kept as environment variables. Examples include DB Connection strings, Secret Keys, decision booleans, etc.

In this article, we will see how to set environment variables in AWS Lambda, using the console, and using the serverless framework.

Method 1 – Using the Console

In the lambda console, navigate to the function of your interest, click on the ‘Configuration’ tab and click on ‘Environment variables’ from the left menu.

AWS Console - Environment Variables

Click on ‘Edit’, then click on ‘Add environment variable’. Enter the name of the variable (key), and its value. Keep adding more variables if required, then click on ‘Save’.

Adding Environment variables in the console

Method 2 – Using Serverless

If you are deploying your function(s) using the serverless framework, you can specify environment variables in the serverless.yml file itself. If you want all the functions to access the environment variables, you can specify them in the provider.

service: my-service

provider:
  name: aws
  stage: dev
  environment: #global
    SECRET_KEY: abcdefgh

functions:
  helloWorld:
    handler: handler.helloWorld

  helloSpace:
    handler: handler.helloSpace

If you want to specify environment variables specific to functions, you can do so by mentioning them against the specific function.

service: my-service

provider:
  name: aws
  stage: dev
  environment: #global
    SECRET_KEY: abcdefgh

functions:
  helloWorld:
    handler: handler.helloWorld
    environment: #specific to helloWorld function
      GREET_WORLD: 0

  helloSpace:
    handler: handler.helloSpace

When you deploy this service, you will see the defined environment variables in the ‘Environment variables’ section of the Configuration tab on the AWS console.

Once the variables are defined, you can access them within your lambda functions in the same way you access environment variables elsewhere. For example, in python, you will use the following line of code:

secret_key = os.environ.get('SECRET_KEY','defaultKey')
world_name = int(os.environ.get('GREET_WORLD',1))

Found this post helpful? Then check out further posts related to AWS here. Also, if you are planning to become a certified AWS Solutions Architect, I’d recommend that you check out this course on Udemy. I took this course and found the lectures to be lucid, to-the-point, and fun. I hope they will help you as well.

Leave a comment

Your email address will not be published. Required fields are marked *