Building AWS Lambda Functions Made Easy: A Guide with AWS CDK

Introduction 

Building and managing Lambda functions can pose challenges, especially when it comes to continuous updates and integration with other AWS services. Thankfully, AWS CDK offers a powerful solution to streamline this process.

In this tutorial, we’ll embark on a journey to master CDK for Lambda development. We’ll learn how to:

  1. Create and initialize a CDK project, setting the stage for your serverless endeavors.
  2. Craft Lambda functions using the expressive power of TypeScript, ensuring efficient and maintainable code.
  3. Effortlessly deploy our Lambda functions to the cloud using CDK’s infrastructure-as-code capabilities.
  4. Add function URLs to effortlessly test and invoke our Lambdas, simplifying the development and debugging experience.

Get ready to unlock a world of streamlined serverless development with CDK!

we’ll be using the same steps as outlined in our previous post for creating the S3 bucket. For those seeking a deeper dive, feel free to click here and revisit the details in our earlier blog.

Steps to Create AWS lambda using CDK V2 (aws cdk)

Step 1: 
  • Create a folder on the Local Drive
  • Open the folder in VSCode Editor
  • Open Terminal
Step 2:  Create the app using aws cdk
  • Make a directory mylambdaAPICdk (or any other based on our choice)

    mkdir mylambdaAPICdk
    
  • Change directory with cd

    cd mylambdaAPICdk    
  • Initialize the app by using cdk init command. Specify the programming language

   cdk init app --language typescript   

aws cdk lambda create project

Step 3:

In the lib/mylambda_api_cdk-stack.ts file

  • Import the modules/packages (All or specific Construct from the Module) for AWS services being created

    import * as lambda from 'aws-cdk-lib/aws-lambda' 
    

Step 4: Define Scope, Logical ID, and Props

  • Scope =this
  • Logical ID = Logical ID Name (Different from physical Id)
  • props – Add the attributes to create the Resources – AWS documentation or Editor code Complete

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class MylambdaApiCdkStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

      // The code that defines your stack goes here 
    

   const lambdaFunction =new lambda.Function(this,'lambdaFunction',{
      handler:'index.handler',
      functionName:'demoLambdaFunction',
      runtime:lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromInline(`
      exports.handler = async (event) => {
        return {
          statusCode: 200,
          body: JSON.stringify({ message: 'Hello, World!' }),
        };
      };
      `)
    })
  }
}
Step 5:  Build the app (optional)

Build (compile) after changing our code.

AWS CDK — the Toolkit implements it but a good practice to build manually to catch syntax and type errors.


    npm run build
    

 

npm run build

Step 6: Bootstrap (One Time): Deploy the CDK Toolkit staging stack in s3 bucket.

   cdk bootstrap
    

cdk bootstrap

Step 7: Synthesize an AWS CloudFormation template for the app.

   cdk synth
    
Step 8: Deploying the Stack (Deploy the stack using AWS CloudFromation)

   cdk deploy
    

After that stack will created in Cloudformation as shown below:

stack deployed

Now we will go to aws lambda service and check lambda has been created or not

Lambda Created using aws cdk

Now we will go to lambda in the aws console and check whether lambda is returning proper response or not.

cdk lambda test response using typescript

Invoking Lambda function with AWS CLI

Now that we have the Lambda function name and have successfully tested its response through the AWS Lambda console, we can easily invoke our Lambda using the AWS CLI as well.


aws lambda invoke --function-name our_lambda_fn_name response.txt   // command

In our case lambda function name is demoLambdaFunction. So our command will look like below:


aws lambda invoke --function-name demoLambdaFunction response.txt   // command

Now let’s execute the command in cmd and wait for a moment.

As a result of executing the command, we can now find a newly generated “response.txt” file within our application directory, meticulously preserving the output generated by our Lambda function.

Adding function URL in Lambda CDK Stack

Add function URL by calling the addFunctionUrl method, passing auth type as none.

Warning: Specifying authType as NONE exposes your API to the public, allowing anyone with the URL to invoke your Lambda function, resulting in associated charges.

After making changes our code would look like the below


import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class MylambdaApiCdkStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // The code that defines your stack goes here

    const lambdaFunction =new lambda.Function(this,'lambdaFunction',{
      handler:'index.handler',
      functionName:'demoLambdaFunction',
      runtime:lambda.Runtime.NODEJS_16_X,
      code: lambda.Code.fromInline(`
      exports.handler = async (event) => {
        return {
          statusCode: 200,
          body: JSON.stringify({ message: 'Hello, World!' }),
        };
      };
      `)
    })

    const fnUrl= lambdaFunction.addFunctionUrl({
      authType:lambda.FunctionUrlAuthType.NONE
    })

    new cdk.CfnOutput(this,'lambda-fun-url',{
      value:fnUrl.url
    })
  }
}

Now we need to deploy our change. So let’s execute the command cdk deploy as we had done previously.

After executing cdk deploy command. We got a new function url shown below.

Now we will copy lambda function URL from cmd and invoke our lambda using Postman.

So, we have now obtained the Lambda response, as depicted in the screenshots above.
Up to this point, we have discussed the creation of a Lambda function using AWS CDK. Now, next post we will delve into the integration of this Lambda function with API Gateway.

Leave a comment