Create and Debug Lambda Function in VS Code

Introduction

I hope everyone is doing well and waiting for the new year 2024. I wish you advance happy new year. Let's start the topic now. 

Today we are going to look at how to develop, debug, and host it into  AWS Lambda functions locally. This is a crucial aspect of efficient serverless application development. With the help of a few tools such as AWS SAM or serverless framework, developers can emulate lambda environment on their local machine.

This allows for rapid iteration and testing before deploying the code base into the cloud. Additionally, tools like AWS CLI and IDE integrations streamline the debugging process, enabling developers to catch and fix issues early in the development lifecycle. This local development approach enhances productivity and ensures the seamless deployment of serverless applications on the AWS Cloud.

Prerequisites

Sl.No Tool(s) Purpose
1 Docker Desktop Docker Desktop allows you to host containers on your local machine, providing a convenient environment for developing, testing, and deploying applications in isolated containers.
2 AWS Serverless Application Model (SAM) The AWS Serverless Application Model (AWS SAM) simplifies the deployment and management of serverless applications on AWS, offering a streamlined YAML-based syntax for defining serverless resources and functions.
3 AWS CLI AWS CLI is a command-line tool that provides a unified interface to interact with various AWS services, enabling users to manage resources, deploy applications, and automate workflows from the command line
4 Visual Studio Code IDE Visual Studio Code is a lightweight yet powerful cross-platform code editor featuring robust language support, extensions, and an integrated debugger, facilitating efficient development across various programming languages.
5 AWS Lambda Templates AWS Lambda Templates are pre-configured code templates, enabling rapid development of serverless functions by providing boilerplate code for common use cases. These templates streamline the creation of AWS Lambda functions, enhancing development efficiency.
6 Amazon.Lambda.TestTool The Amazon.Lambda.TestTool is a command-line interface tool that facilitates local testing and debugging of AWS Lambda functions by simulating Lambda runtime environments on a developer's machine. It helps streamline the development process by providing a local testing environment for Lambda functions before deployment to the AWS Cloud.

Implementation Lambda function

1. Open the Visual Studio Code and Navigate to Terminal; install the template using the following command. 

dotnet new --install Amazon.Lambda.Templates

Once you installed it, you can create the below templates in your local machine.

 Templete

2. Install the Lambda test Tool. Please make sure it's installed in your system successfully because this tool will trigger an entry page to test our code base. I will show you the page below steps.

dotnet tool install -g Amazon.Lambda.TestTool-6.0

3. Create a new Lambda function we are using.

dotnet new lambda.EmptyFunction -n Lambda-demo

Once the above line of code, the project files are created, and it will be like below. 

Project file

4. Modify the Function Handler. Added line #9 to log into the trace, which will show you where we see this logger as output. 

/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <returns></returns>
public string FunctionHandler(string input, ILambdaContext context)
{
    Console.WriteLine("Trace: FunctionHandler executed");
    return input.ToUpper();
}

5. Build the project to see if any error exists in the code base.

dotnet build
MSBuild version 17.7.3+8ec440e68 for .NET
  Determining projects to restore...
  Restored C:\Repository\lambda-demo.csproj (in 177 ms).
  lambda-demo -> C:\Repository\lambda-demo\bin\Debug\net6.0\lambda-demo.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.25

6. Add the launch.json file. You can create this file either manually or while you click on start debug. The system prompts you to add the add launch.json file. 

{
    "version": "1.0.0",
    "configurations": [
        {
            "name": "lambda-demo launch",
            "type": "coreclr",
            "request": "launch",           
            "program": "${env:USERPROFILE}/.dotnet/tools/dotnet-lambda-test-tool-6.0.exe",
            "args": [],
            "cwd": "${workspaceFolder}",
            "console": "internalConsole",
            "stopAtEntry": false,
            "internalConsoleOptions": "openOnSessionStart",
            "requireExactSource": false
        }
    ]
}

It's time to Run and debug the code. Put the breakpoint in Functional Handler or whichever line of code you feel works for you. 

In the debug console, it says the application is running at http://localhost:5050/

Debug console

7. Pass the input and click on the execution function button. It will hit the breakpoint as shown below snippet and you can see the trace log in the log output section. 

Log

8. It is time to use the Serverless Application Model  now

  • Please use this command to check if SAM is installed on your machine.
sam --version

9. Try to do something with SAM which is used to deploy it in docker as a container

  • Create template yaml file before doing sam build
  • Create an event folder and add event.json to pass the event data for testing at runtime.
sam build

Once executed the sam build is done, the system will create a build file in root direct as .aws-sam, which contains the following files. please refer to the snippet.

Sam build

10. Now, it's time to execute and test our work.  

sam local invoke -e events/event.json

Testing

11. Once happy with our local development, let's move our code to the cloud environment using the following commands

  • Configure cloud access key, secret key, and region
    aws configure
  • Navigate to the source code path and execute the below code to deploy in a cloud environment
  • we can opt to deploy with two options one is sam deploy -g, and another option is like the below  
    dotnet lambda deploy-function
  • Enter the new lambda function name 
  • Enter the new IAM Role
  • Select IAM Policy to attach to the new role and grant permissions: Since it is POC, opt-in "*** No policy, add permissions later ***"
    Waiting for new IAM Role to propagate to AWS regions
    ...............  Done
    New Lambda function created

12. It's time to validate on the cloud environment. please navigate to the respective region and lambda section. please find the snippet below.

Function overview

To test the environment, please follow the below snippet

Test event

Conclusion

AWS SAM and Lambda empower developers to embrace serverless computing without sacrificing control or scalability. Whether you are a seasoned developer or just starting with serverless architecture, the AWS SAM and Lambda Duo offer a robust and efficient framework for building modern, cloud-native applications. As serverless continues to shape the future of cloud computing, AWS SAM and Lambda remain at the forefront, providing a solid foundation for innovation and agility in the world of serverless development.

Thanks for reading. I will catch up on the next article until then, bye for now.


Similar Articles