Debabrata Mondal
Debabrata Mondal

Reputation: 101

How to add environment variables to lambda function that is being developing locally?

I have started to build a lambda function locally using the AWS Toolkit in VS Code. I want to make requests to an external API with requires an API key.

I am having some problem storing the key. According to the docs, I can set the environment variable from the AWS Console or CLI. But I have not deployed the function yet and am just trying to invoke it locally. Any pointers on how I can store and access the API key?

The function is built on node.js

Upvotes: 1

Views: 1492

Answers (2)

Redtopia
Redtopia

Reputation: 5237

Here's my approach:

First step, create a .env file in the root directory of your function, in the same directory where package.json is located (and your function's .js file). For this example, my .env file contains one variable as follows:

SQL_SERVER_DB="TestDB"

Next step, in your package.json file, add the dotenv dependency (i've used the latest version as of this answer):

"dependencies": {
    "dotenv": "^16.0.3"
}

In your lambda function, figure out if you're running locally or not:

// see if we're running local or in aws lambda
const isLocal = process.env.AWS_SAM_LOCAL === 'true';

// configure sqlConfig with environment vars
let sqlConfig = {
    database: ''
    // ... etc
}

I added this variable as a global to the beginning of the file, before the main lambda function definition.

At the beginning of my lambda function, I call:

loadEnvironmentVars();

which is defined as:

Note: I defined sqlConfig as a global object before I call this function. That's because this object will be updated with environment variables.

function loadEnvironmentVars () {

    console.log("load environment vars, isLocal: " + isLocal);

    if (isLocal) {
        // read the env variables from the .env file and parse them
        // note: env vars are set differently when running in lambda
        try {
            dotenv.config();
            // Read and parse the .env file
            const envBuffer = fs.readFileSync('.env');
            const envConfig = dotenv.parse(envBuffer);
            // Load the environment variables into process.env
            for (const key in envConfig) {
                process.env[key] = envConfig[key];
                console.log("env variable found: " + key + "=" + process.env[key]);
            }
        } catch (err) {
            console.log("Failed to load local .env variables: " + err.message);
        }
    }

    // set your environment vars used in this lambda function here:
    
    // note: sqlConfig is a global object!
    sqlConfig.database = process.env.SQL_SERVER_DB ? process.env.SQL_SERVER_DB : '';

}

When running locally, after loadEnvironmentVars() is called, the sqlConfig.database property should be set to "TestDB".

When Running In AWS Lambda (Production)

You will also need to set your environment variables in AWS Lambda in order for your code to work in both development and in production. You can learn how to do this here:

https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html

Source Control

Make sure your local .env file is not included in your source control repository.

Upvotes: 1

Jyothish
Jyothish

Reputation: 1133

You can store the API key in AWS secret manager and retrieve the secret in your code. Make sure that the profile you are using in VS has permissions. You can refer Retrieving AWS secrets using Visual Studio toolkit

Upvotes: 2

Related Questions