Skip to content

Introduction

To take advantage of Lightrun’s functionality in your AWS Lambda function, you must deploy Lightrun’s agent library with your project. One of the ways to import the additional code (frameworks, SDKs, libraries, and more) into a Lambda function is to bundle the function with an AWS Lambda Layer.

In this tutorial, we will learn how to package the Lightrun Node.js agent into a Lambda layer. We will also demonstrate how to attach the Lambda layer to your AWS Lambda function in other to be able to import and use Lightrun in your project.

Note

These instructions are valid only for AWS Lambda functions deployed as a .zip file archive.

Prerequisites

This tutorial assumes that you have:

Create a Lambda layer

AWS Lambda Layer is a .zip archive containing libraries, configuration files, dependencies, etc., that you can import at runtime into your Lambda function. To create an AWS Lambda layer for the Lightrun Node.js agent, we must compile the Lightrun Node.js agent into a .zip archive and then upload the .zip file archive to AWS via the AWS console or with the AWS CLI.

Compile the Lightrun Node.js agent into a .zip archive

The first step when creating an AWS Lambda layer is to bundle the layer’s content into a .zip file archive. To set up a .zip file for the Lightrun Node.js agent, first, create a new directory that will be used to store the dependencies that will go into the Lambda layer.

mkdir lambda_layer
cd lambda_layer

Initialize npm in the directory. A package.json file will be generated to the directory.

npm init -y

Install Lightrun

npm install lightrun

After installing Lightrun, a node_modules folder will be added to the directory. Add the following build script to your package.json file.

"scripts": {
"build": "npm install && mkdir -p nodejs && cp -r node_modules nodejs/ && zip -r  layers.zip nodejs"
}

Note

Installed dependencies in a Node.js Lambda layer must be stored in a nodejs/node_modules/{our libraries} or nodejs/<node-version>/node_modules/{our libraries} file path for the dependencies to be discovered by a Node.js Lambda function. You can learn more about Lambda layer paths here.

Generate your .zip file.

npm run build 

A layers.zip file will be added to the lambda_layer folder.

Create a Lambda layer for the Lightrun Node.js agent

After compiling the Lightrun Node.js agent into a .zip file archive. The next step will be to create our AWS Lambda layer. We can deploy the .zip file to AWS in two ways:

Create a Lambda layer from the AWS console

To create an AWS Lambda layer from your AWS console.

  1. Navigate to the AWS Lambda console, and open the Layers page of the console.
  2. Click Create Layer.
  3. Specify a name for the new Lambda Layer.
  4. Upload the layers.zip file.
  5. Select the compatible architecture and runtime for your .zip file (we will be using the x86_64 architecture and nodejs14.x as our preferred runtime environment).
  6. Click Create.

    The new Lambda Layer is now available to your Node.js Lambda functions.

Create a Lambda layer with the AWS CLI

Note

The following instructions assume that you have the AWS CLI installed on your local machine. Follow the instructions here to install and set up the AWS CLI on your local machine if you haven’t already installed it.

Create the AWS Lambda layer with the AWS CLI with the following command.

aws lambda --region us-east-1  publish-layer-version --layer-name 'Lightrun_Package_node' --compatible-runtimes 'nodejs14.x' --zip-file fileb://layers.zip

Change Lightrun_Package_node1 to your preferred layer name, change us-east-1 to your preferred region, and nodejs14.x to your desired Node.js runtime environment.

If the deployment was successful, you should get a similar response to this in your terminal.

{
    "Content": {
        "Location": "<aws_location_key>",
        "CodeSha256": "DvW8+mrWOf9T5OAQkaekXpjpSVF4RbkFCiMo33o/BHA=",
        "CodeSize": 4430628
    },
    "LayerArn": "<layers_arn>",
    "LayerVersionArn": "<layers_version_arn>",
    "Description": "",
    "CreatedDate": "2022-06-16T12:13:50.087+0000",
    "Version": 1,
    "CompatibleRuntimes": [
        "nodejs14.x"
    ]
}

Important

Note the LayerVersionArn key that I highlighted above. We will use the key to bundle the Node.js agent Lambda layer into our Lambda functions if we want to deploy our Lambda function directly from the AWS CLI.

Share the Lambda layer to your application

Now that we have created a Lambda layer for the Lightrun Node.js agent, the next step will be to add the Lambda layer to our Node.js Lambda function to be able to debug the Lambda function with Lightrun. We can do this in two ways.

Add the Node.js agent Lambda layer to your application from the AWS Console

If you have already deployed your Node.js function to AWS, you can easily attach the Lambda layer to the Lambda function in your AWS Console. First open the Functions page in your AWS Lambda console, and select the relevant Lambda function.

Click Configurations, select Environment variables, and click Edit to add a new environment variable. Set the variable name to LIGHTRUN_SECRET and copy the value from your management portal.

Environment variables

Environment variables

Then, add the following code samples to the function Code source.

const lightrun = require("lightrun");

async function lightrunStart() {
  try {
    await lightrun.start({
          lightrunSecret: process.env.LIGHTRUN_SECRET,
          lightrunWaitForInit: true, 
          lightrunInitWaitTimeMs: 10000,
          metadata: {
            registration: {
               displayName: "<lambda_function_name>",
               tags: ['<lamda_function_name>']
            }
          }
      });
      console.log('lightrun started');
  } catch(err) {
    console.log("error starting Lightrun", err);
  }

Note

Change <lambda-function-name> to your Lambda functions name.

Important

AWS Lambda functions are event-driven short-running programs with a maximum execution time of 15 minutes. To debug AWS Lamda functions with the Lightrun Python agent:

  1. Specify lightrunWaitForInit: true and lightrunInitWaitTimeMs: 10000 in the Lightrun Node.js agent configuration. These two configuration parameters will ensure that the Lightrun agent starts up fast enough to work with the short-running AWS Lambda functions and also apply a wait time of about 10000 milliseconds before fetching Lightrun actions from the server.

  2. Apply Metadata tags that include the name of your Lambda function - By default, a new Lightrun agent is created whenever the Lambda function is invoked. By adding our function’s name as a metadata tag, we can attach Lightrun actions to agents created whenever the Lambda function is invoked, even before the Lambda function is invoked. This is because an action bound to a metadata tag is implicitly attached to all agents possessing that tag.

Call the lightrunStart() function in your exports.handler function, and click Deploy to update the code source.

exports.handler = async (event, context) => {
  const lightrun = await lightrunStart();
  console.log(lightrun);

Finally, to attach the Lightrun Node.js agent layer to the Lambda function, scroll down to the Layers section, and select Add a layer. Click Custom layers and select the appropriate layer from the drop-down list. Pick a version and click Add to attach the layer to your Lambda function.

Node layers

Add the Node.js agent Lambda layer to your application from the AWS CLI

Note

  • The following instructions assume that you have the AWS CLI installed on your local machine. Follow the instructions here to install and set up the AWS CLI on your local machine if you haven’t already installed it
  • Ensure that you have configured all the permissions required to run an AWS Lambda function and created a role for the Lambda function. Learn more about the permissions needed to deploy a Lambda function here. Follow the instructions here to create a Lambda execution role for your Lambda function.

If you haven’t deployed your Lambda function to AWS, you can easily attach the Lambda layer to your application during deployment with the AWS CLI. To demonstrate how to add the created Lambda layer to a Node.js function deployed with the AWS CLI, we will deploy a simple demo application as an AWS Lambda function with the Lambda layer added to it.

To create the demo application, create a folder for the application.

mkdir node_lambda_function
cd node_lambda_function

Add an index.js file to the folder.

touch index.js

Add the following code samples to the index.js file.

const lightrun = require("lightrun");

async function lightrunStart() {
  try {
    await lightrun.start({
          lightrunSecret: process.env.LIGHTRUN_SECRET,
          lightrunWaitForInit: true,
          lightrunInitWaitTimeMs: 10000,
          metadata: {
            registration: {
               displayName: "node-lambda-function",
               tags: ['node-lambda-function']
            }
          }
      });
      console.log('lightrun started');
  } catch(err) {
    console.log("error starting Lightrun", err);
  }
}

exports.handler = async (event, context) => {
  const lightrun = await lightrunStart();
  console.log(lightrun);
    console.log("Start sleeping in loop");
    for (let i = 0; i < 10000; i++) {
        await new Promise(r => setTimeout(r, 5000));
        console.log("tick");
    }
};

Note

Change <lambda-function-name> to your Lambda functions name.

Important

AWS Lambda functions are event-driven short-running programs with a maximum execution time of 15 minutes. To debug AWS Lamda functions with the Lightrun Python agent:

  1. Specify lightrunWaitForInit: true and lightrunInitWaitTimeMs: 10000 in the Lightrun Node.js agent configuration. These two configuration parameters will ensure that the Lightrun agent starts up fast enough to work with the short-running AWS Lambda functions and also apply a wait time of about 10000 milliseconds before fetching Lightrun actions from the server.

  2. Apply Metadata tags that include the name of your Lambda function - By default, a new Lightrun agent is created whenever the Lambda function is invoked. By adding our function’s name as a metadata tag, we can attach Lightrun actions to agents created whenever the Lambda function is invoked, even before the Lambda function is invoked. This is because an action bound to a metadata tag is implicitly attached to all agents possessing that tag.

Finally, deploy the index.js file as an AWS Lambda function. You can do this in two ways.

Deploy the index.js file as a .zip file archive

To deploy the index.js file as a .zip file archive, first, zip the index.js file.

zip function.zip index.js

Then, deploy the function with the following command.

aws lambda create-function \
--region us-east-1  \
--function-name node3 \
--zip-file fileb://function.zip \
--role <lambda_execution_role_arn> \
--handler index.handler \
--runtime nodejs14.x --timeout 10 --memory-size 512 \
--layers <LayerVersionArn> \
--environment Variables="{LIGHTRUN_SECRET=<LIGHTRUN_KEY>}"

Update the command with the following values:

  • --function-name - Lambda function name.
  • --role - Lambda execution role ARN. (Follow the instructions here to create a Lambda execution role for your Lambda function.)
  • --runtime - Preferred Node.js runtime environment.
  • --layers - Lambda layer Version ARN
  • --environment Variables - Lightrun secret Keys.

Note

You can get your LIGHTRUN_KEY from your Lightrun Management portal.

Keys

If your deployment was successful, you should get a response similar to this.

{   
    "FunctionName": "node3",
    "FunctionArn": "arn:aws:lambda:us-east-1:<iam-user>:function:node3",
    "Runtime": "nodejs14.x",
    "Role": "arn:aws:iam::<iam-user>:role/lmb",
    "Handler": "index.handler",
    "CodeSize": 494,
    "Description": "",
    "Timeout": 100,
    "MemorySize": 512,
    "LastModified": "2022-06-20T08:22:44.022+0000",
    "CodeSha256": "d4hbbWI60FaCd0SfMLTCv+X2f33kM8sTzsC7lYp6LTc=",
    "Version": "$LATEST",
    "Environment": {
        "Variables": {
            "LIGHTRUN_SECRET": <LIGHTRUN_KEY>
        }
    },
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "RevisionId": "f97c70b1-7ce7-48e6-92f5-3ba159cb2cf6",
    "Layers": [
        {
            "Arn": "arn:aws:lambda:us-east-1:<iam-user>:layer:Lightrun_Package_node1:1",
            "CodeSize": 4430628
        }
    ],
    "State": "Pending",
    "StateReason": "The function is being created.",
    "StateReasonCode": "Creating",
    "PackageType": "Zip",
    "Architectures": [
        "x86_64"
    ],
    "EphemeralStorage": {
        "Size": 512
    }

Deploy the index.js file as an AWS SAM application

Alternatively, you can deploy the index.js file by packaging it as an AWS SAM template.

Prerequisites

The following instructions assume that you have the AWS SAM CLI and Docker installed on your local machine. - Follow the instructions here to install the AWS SAM CLI on your local machine. - Follow the instructions here to setup Docker on your local machine.

Add a template.yaml file to the node_lambda_function folder.

touch template.yaml

Add the following yaml to the template.yaml file.

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  NodeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs14.x
      Role: <lambda_execution_role_arn>
      Layers:
        - <LayerVersionArn>
      Environment:
        Variables:
          LIGHTRUN_SECRET: <LIGHTRUN_KEY>

Update the YAML file with the following values.

  • NodeFunction - change to your preferred Lambda function’s name.
  • Role - Lambda execution role ARN. (Follow the instructions here to create a Lambda execution role for your Lambda function.)
  • Runtime - Preferred Node.js runtime environment.
  • Layers - Lambda layer Version ARN
  • Environment/Variables - Lightrun secret Keys

Note

You can get your LIGHTRUN_KEY from your Lightrun Management portal.

Keys

Run the following command to build the SAM template.

sam build

Run the following command to deploy the SAM template.

sam deploy --guided

And now you've added a Lightrun agent to your Node.js Lambda function! Install our plugin to get started adding Lightrun Actions to your application.


Last update: March 16, 2023