Table of Content
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`,
};
}
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:
lambda
directory.hello
.handler
.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
The IAM statement and resources in red will be deleted.
The IAM statement, IAM policy and resources in green will be created.
Run cdk deploy
to deploy your CDK stack with the hello world lambda function.
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
.
Check the CdkWorkshopStack
in CloudFormation Console to verify that HelloHandler
and a HelloHandlerServiceRole
is created.
Click on the HelloHandler
Physical Id to open the detail page of the Lambda function.
Open the Test
tab, click Test
button to invoke your HelloHandler
.
Check the detail to verify HelloHandler
is invoked succeeded.
Now, you have used CDK to deploy
In the next step, you will deploy your list-users
handler that interact with a DynamoDB.