Managing .NET Core AWS Lambda With TypeScript AWS CDK

The guide demonstrates how to manage AWS Lambda function written in .NET Core with AWS CDK script written in TypeScript

Monday, October 21, 2019

Full source code can be found at https://github.com/mgjam/blog/tree/master/1-final.

Project Bootstrap

For the purpose of this guide, lets have following solution structure cdk folder will contain the TypeScript CDK scripts. src folder will contain .NET Lambda code.

To install CDK CLI, follow instructions on https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html. To create a CDK app, execute

..app\cdk> cdk init --language TypeScript

Generated template is ready to be extended for your stack needs.

To install AWS Lambda .NET Core CLI, follow instructions on https://docs.aws.amazon.com/lambda/latest/dg/lambda-dotnet-coreclr-deployment-package.html. To create a Lambda project, execute

..app> dotnet new Lambda.EmptyFunction

By now the solution should like the one at https://github.com/mgjam/blog/tree/master/20191021-1-solution-structure

Lambda Publish

Publishing of lambda generates dll files which can be then referenced by the CDK script. To publish your created lambda, execute

..app\src\app> dotnet publish app.csproj -c Release

The command will publish your lambda function with Release configuration into your folder. Publish output path for .NET Core 2.1 app will be
..\app\src\app\bin\Release\netcoreapp2.1\publish\

CDK

Lambda package needs to be installed to define your lambda function resource. List of available packages can be found at https://docs.aws.amazon.com/cdk/api/latest/docs/aws-construct-library.html. To install lambda package, execute

..app\cdk>npm install @aws-cdk/aws-lambda

Now you can open your cdk-stack.ts file to define your resources code property needs to be set to the lambda publish folder path. handler property needs to be set in format of <dllName>::<namespace>.<className>::<classMethod>. Remember to run npm run build to compile your TypeScript into JavaScript unless you have code watch on.

Before being able to deploy your stack, CDK needs to have it's boostrapping done. To do so, execute

..app\cdk> cdk bootstrap

Now you can deploy your stack into AWS by executing

..app\cdk> cdk deploy

You can now log into your AWS Lambda management console and test deployed lambda.

Closing Notes

The CDK configuration is very simplified just to show key concepts of referencing .NET Lambda in CDK scripts. Additional information can be found at
https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-readme.html