C# Lambda With CDK Pipelines

For a while a colleague and myself have been trying to figure out how to get a .Net lambda deployed using CDK pipelines. Unfortunately, the AWS documentation only shows how to write the pipeline in C# to deploy a Node lambda. If anyone from AWS is reading this, that isn’t a very useful example, if you are using C# for your pipeline, it is very likely that you will also want to deploy a lambda written in C#.

There was a new feature added to CDK in 2020 called bundling which seems to now be the correct way for deploying lambdas via CDK. With bunding CDK downloads an AWS container, map the source folder to that container, I then use dotnet publish which builds the code in the container. The output from the the .Net publish command is put in the containers /asset-output folder. This is used by the pipeline to get the compiled code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
IEnumerable<string> commands = new[]
{
"cd /asset-input",
"dotnet publish -c Release -r linux-arm64 -p:PublishReadyToRun=true -o /asset-output"
};

var function = new Function(this, "example-lambda", new FunctionProps
{
FunctionName = "ToUpper-Lambda",
Description = "Changes input to upper case",
Runtime = Runtime.DOTNET_CORE_3_1,
Handler = "ExampleLambda::ExampleLambda.Function::FunctionHandler",
Architecture = Architecture.ARM_64,
Code = Code.FromAsset("./ExampleLambda/", new AssetOptions
{
Bundling = new BundlingOptions
{
Image = Runtime.DOTNET_CORE_3_1.BundlingImage,
Command = new []
{
"bash", "-c", string.Join(" && ", commands)
}
}
})
});

Once you have the lambda stack set up, create a stage for the lambda deployment. When this is added to the pipeline you will notice that an Assets stage is added to the pipeline.
Assets

The other thing you need to do is make sure the step that synth stack is run in a CodeBuildStep, not a ShellStep. It also needs to be privileged as this is the step that will build the lambda code inside a container as well synth the stack.

When you run the pipeline you will see the lambda is built in the build stage, then the lambda is taken from the build assets and moved into it’s one asset/s3 key so that it can be passed to the cloudformation stack that cdk creates.

I’ve put the full example on Github