Looking for Senior AWS Serverless Architects & Engineers?
Let's TalkIntroduction
This article will cover creating a lambda function with AWS CDK and deploying it to the AWS console. AWS CDK allows you to build reliable, scalable, cost-effective applications in the cloud with the help of a programming language.
It gives the ability to describe your infrastructure with code using your favorite programming language. Currently, it supports TypeScript, JavaScript, Python, Java, C#/.Net, and ( in developer preview) Go. You can access this article's FREE template for download HERE.
Prerequisites
- An AWS Account
- AWS CLI configured
Installing the CDK
Run the below command to install the CDK node package to use the AWS CDK command through the CLI.
Creating a project
Create an empty directory and initialize the project with the CDK.
Once initialization is done, it will generate many files and install the required dependencies like below.
Let's Talk About the Files We Will Be Working With (Most of the Time):
lib/cdk-test-stack.js - This is the file where our CDK stack is defined and where we will be creating our aws resources.
bin/cdk-test.js - This is the entry point of the application and will load the stack defined in lib/cdk-test-satck.js
test/cdk-test.test.js - This is where we will write test cases.
Create The Lambda Function
Modify the file lib/cdk-test-stack.js to create our NodeJS lambda function. Update the code with the below one:
Install a node module for lambda - npm i @aws-cdk/aws-lambda
Let's See What We Are Doing Above:
We are creating a lambda function called cdkLambdaTest with runtime NodeJS14. Lambda timeout is set to 300sec, memory size is 1GB, and the property code indicates the path of code for lambda.
Now, Let’s create a folder called src with an index.js file and update it with the code:
Deploy the Stack:
The first step is to generate the CloudFormation template with the command:
The above command will output the CloudFormation stack within the project like below:
The next step is to bootstrap the environment. This will create a stack that includes resources used for toolkit operation.
Note- This command is required only if it is the first time you are deploying with the CDK. Skip if already been done before.
Once the above step is done, deploy the stack with the command:
It will output the stack in console and ask permission to deploy, press y to continue.
Once the process is completed, go to the AWS console and check your lambda.
The above image shows that Lambda is successfully deployed.
Conclusion
In this article, we have seen how to create Lambda functions using AWS CDK and deploy them to aws console. With CDK you can customize, share and reuse constructs within your organization, and it helps to define your infrastructure with code and provision it through AWS CloudFormation.
Please refer to the documentation for more information. The complete code for this article can be found here.
Sources: