Deploy a hello world Lambda function

Table of Content

Add function code for Lambda function

  • Create a lambda directory in root of your CDK project.

  • In the lambda directory, create a hello.mjs file with the following content:

    export async function handler(event) {
      console.log("request:", JSON.stringify(event, undefined, 2));
      return {
        statusCode: 200,
        headers: { "Content-Type": "text/plain" },
        body: `Hi, CDK! You've hit ${event.path}\n`,
      };
    }
    

Add CDK code for Lambda function

  • Update the main stack at lib/cdk-workshop-stack.ts:

    import { Stack, StackProps } from "aws-cdk-lib";
    import { Construct } from "constructs";
    import { Code, Function, Runtime } from "aws-cdk-lib/aws-lambda";
    
    export class CdkWorkshopStack extends Stack {
      constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);
    
        const hello = new Function(this, "HelloHandler", {
          runtime: Runtime.NODEJS_22_X,
          code: Code.fromAsset("lambda"),
          handler: "hello.handler",
        });
      }
    }
    

    Your CDK stack now contains a HelloHandler Lambda function that:

    • use the code from lambda directory.
    • the file is hello.
    • the function name is handler.

[Optional] Run cdk diff to check the difference of your CDK stack

  • Use cdk diff to compare the difference between the stack in your CDK app with the deployed CDK stack (in your AWS account)

    cdk diff
    

    alt text

    • The IAM statement and resources in red will be deleted.

      alt text

      alt text

    • The IAM statement, IAM policy and resources in green will be created.

      alt text

      alt text

Run cdk deploy to deploy your CDK stack with the lambda function

  • Run cdk deploy to deploy your CDK stack with the hello world lambda function.

    alt text

If you have deployed the CDK stack (by running cdk deploy), cdk deploy will update the deployed stack to match the local stack. In other words, CDK will: 1. compare the local stack with the deployed stack (to get a change set); 2. apply these change set to your deployed stack

  • To confirm, type y and press Enter.

    alt text

Verify Lambda function is deployed and test it

  • Check the CdkWorkshopStack in CloudFormation Console to verify that HelloHandler and a HelloHandlerServiceRole is created.

    alt text

  • Click on the HelloHandler Physical Id to open the detail page of the Lambda function.

    alt text

  • Open the Test tab, click Test button to invoke your HelloHandler.

    alt text

  • Check the detail to verify HelloHandler is invoked succeeded.

    alt text

  • Now, you have used CDK to deploy

    • a Lambda function
    • a SQS queue
    • a SNS topic
  • In the next step, you will deploy your list-users handler that interact with a DynamoDB.