Getting Started with AWS Lambda Environment Variables

Published:30 December 2022 - 6 min. read

Michael Nguyen Tu Image

Michael Nguyen Tu

Read more tutorials by Michael Nguyen Tu!

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Does adjusting your function’s behavior without messing up your code sound impossible? Well, not unless you have the right tools, like AWS Lambda environment variables.

As key-value pairs, you can dynamically pass these variables to your function’s runtime. In turn, you enable the code to behave differently based on the values set at execution time. And this tutorial will walk you through how to set and use environment variables in a Lambda function.

Dive in and improve the flexibility and scalability of your applications!

Prerequisites

This tutorial comprises hands-on demonstrations. To follow along, you will need an AWS account and access to the AWS Management Console — a free tier account is sufficient.

Creating an IAM User

AWS Lambda environment variables are a great way to customize your serverless application. But before taking advantage of these environment variables, you need an IAM (Identity and Access Management) user. This user allows you access to AWS services through the Management Console.

You will create an IAM user with administrator access to configure environment variables for your Lambda functions. Using a root user is possible, but creating a user with limited access is the best practice security-wise.

To create an IAM user for configuring your environment variables, follow these steps:

1. Open your favorite web browser, and log in to the AWS Management Console with your root user.

2. Navigate to the IAM dashboard and select Users (left panel), and click Add User to add a new IAM user.

Initiating adding a new IAM user
Initiating adding a new IAM user

3. Provide a User name (e.g., aws-lambda-variables-user), and tick the Password – AWS Management Console access checkbox under Access Type. This type of access lets your user access the Management Console with their username and password.

Keep other settings as is, and click Next: Permissions to continue.

Setting user details
Setting user details

4. Now, select the Attach existing policies directly option, tick the AdministratorAccess checkbox, and click Next: Tags to continue. This option gives your IAM user full access to all AWS services.

Setting IAM user permissions
Setting IAM user permissions

5. On the next page, add optional tags (optional) to your user for easy identification, and click Next: Review to review your settings before creating the user.

Adding tags (optional)
Adding tags (optional)

6. Next, review your selected settings, and click Create User to finish creating the new IAM user.

Creating the new IAM user
Creating the new IAM user

Once created, you will see a green success message, as shown below.

Verifying the new IAM user has been created
Verifying the new IAM user has been created

7. Now, click Download .csv to save your new IAM user credentials (username and password) in a CSV file. Ensure you save this file safely and securely, and never share the credentials in GitHub or other public places.

Once downloaded, note the URL and password, as shown below. You will need them to log in with your new IAM user.

Downloading the IAM credentials in a CSV file
Downloading the IAM credentials in a CSV file

Creating a Lambda Function

Now that you have your IAM user with administrator access, you are ready to create a Lambda function. Lambda functions are serverless computing services that let you run code without managing servers. For instance, you can use a Lambda function to process events and run your code in response to these events.

In this tutorial, you will create a simple Node.js Lambda function that prints out an environment variable. You will later use this function to demonstrate environment variables in a Lambda context.

1. Open the URL you noted in the last step of the “Creating an IAM User” to a new browser tab and sign in with your IAM user’s credentials.

💡 Signing in as the new IAM user in the incognito mode best prevents cached credentials from interfering.

Signing in to the AWS console as the new IAM user
Signing in to the AWS console as the new IAM user

2. Next, navigate to the AWS Lambda dashboard, and click Create Function to create a new AWS Lambda Function.

Initiating creating a new AWS Lambda function
Initiating creating a new AWS Lambda function

3. Lastly, configure the function with the following:

  • Select the Author from scratch option to start with a basic function example.Enter a Function name (e.g., Print-AWS-Lambda-Env-Variable).Select a Node.js version (e.g., 16) as a Runtime for your function. This runtime is the environment where your code will be executed.
Keep all other settings as is, and click Create Function to finish creating your function.

Configuring an AWS Lambda Function
Configuring an AWS Lambda Function

If successful, your browser redirects to a page like the one below. Congratulations! You have created your first AWS Lambda Function.

Do not close this page yet, though. In the following sections, you will use this page to configure the environment variables for your function.

Verifying the newly-created AWS Lambda Function
Verifying the newly-created AWS Lambda Function

Configuring and Testing an AWS Lambda Environment Variable

With your first AWS Lambda Function created, it is time to work on AWS Lambda environment variables. You can use environment variables to configure your applications without hard-coding any sensitive information.

In this example, you will configure an environment variable and make your function print out this variable to the console when executed.

To configure an AWS Lambda environment variable:

1. Navigate to the Configuration tab inside your function to view its configuration page, click Environment Variables (left panel), → Edit to edit the function’s environment variables.

Editing the function’s environment variables
Editing the function’s environment variables

2. Next, enter a key-value pair in the Key and Value fields to configure an environment variable with the following requirements in mind:

  • The Key (e.., ENV_VAR) should not contain any special characters except for underscores.The Value (Hello World123!) can include any text or numbers, but you must begin with a letter and should not contain sensitive data such as API keys, passwords, etc.Do not duplicate reserved variable names (e.g., AWS_REGION). Reserved names are predefined variables managed by AWS Lambda. Using a reserved name can cause unexpected behavior or total failure of the Lambda function.
Once configured, click Save to save the changes.

Editing environment variables
Editing environment variables

You will see a green success message indicating you have successfully updated your environment variable.

Verifying successful environment variable update
Verifying successful environment variable update

3. Click the Code tab, as shown below, populate the code below into the index.js file, and click Deploy to save your changes and deploy your function.

This code reads and prints the environment variable you configured as a response.

// This exports.handler function is an async function that is designed to be used
// as the entry point for an AWS Lambda function. The function retrieves the value
// of the AWS_REGION environment variable, which is set by AWS and contains
// the region where the Lambda function is running. The function then constructs
// a response object that includes the value of the AWS_REGION variable, and returns
// the response to the caller. This function allows the caller to see which region
// the Lambda function is running in.
exports.handler = async (event) => {
 // Retrieve the value of the AWS_REGION environment variable using the process.env
 // object, which provides information about the currently running Node.js process.
 const ENV_VAR = process.env.ENV_VAR;
 // Create a response object that includes the value of the AWS_REGION variable. The
 // response object has a statusCode property, which is set to 200 to indicate that
 // the request was successful, and a body property, which contains a string that
 // includes the value of the AWS_REGION variable.
 const response = {
     statusCode: 200,
     body: `The value of ENV_VAR is: ${ENV_VAR}`
 };
 // Return the response object to the caller.
 return response;
};
Deploying the function
Deploying the function

4. Now, click Test to open the Test Events window, where you can simulate events that trigger your code execution.

Accessing the Test events window
Accessing the Test events window

5. Finally, select the Create new event option, provide a name for the event (e.g., myevent), keep all the default settings, and click Test (top-right). This action runs the function with your newly created event.

Testing the function with your newly created event
Testing the function with your newly created event

If everything is set up correctly, you will see a succeeded message, as shown below, with all other kinds of information, like the Request ID, Memory Used, and so on. But the most important ones are your environment variable and its value printed in the black response body section.

See your environment variable and its value? Congratulations! You have successfully configured an environment variable for your AWS Lambda Function.

Testing the environment variable in an AWS Lambda Function
Testing the environment variable in an AWS Lambda Function

Using Reserved Environment Variable Names

Since you cannot use reserved environment variable names as your own, can you use them in your functions instead? Yes! You can use any of the reserved environment variables in your functions to access information.

The predefined AWS Lambda environment variables include but are not limited to AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and more.

Test the below code in your function to print which region (AWS_REGION) your Lambda function is running in.

 exports.handler = async (event) => {
 const AWS_REGION = process.env.AWS_REGION;

 const response = {
     statusCode: 200,
     body: `Your region is: ${AWS_REGION}`
 };
 return response;
};

Below, you can see your region displayed in the response body.

Checking the region using the Lambda function
Checking the region using the Lambda function

Conclusion

AWS Lambda environment variables let you quickly make changes to your function on the fly. And in this tutorial, you have learned how to create and configure environment variables in your AWS Lambda function.

With environment variables, you can make your AWS Lambda Functions more adaptable. Now, why not secure your environment variables by using AWS Key Management?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!