Skip to content

Katarzyna Kmiotek

AWS Lambda in .NET with Terraform

Tutorial, AWS1 min read

Deploying your AWS Lambda functions with the Terraform module terraform-aws-modules/lambda/aws takes away all hassle with installing your dependencies, building project and zipping directory before deploying to AWS. It also allows you to use other sources for your zip package - from the local file, from s3 and supports layers. Their documentation has examples for NodeJS and Python runtimes but my requirement was Lambda in .NET and I struggled to find an example that would show me how to deploy lambda without the need for zipping the directory manually or in a separate job in the pipeline.

This example assumes you have your function written in .NET, your Terraform is set with AWS provider and you planning to deploy locally or in the pipeline via Terraform (terraform apply).

Your .csproj file should contain the attribute:


When you use this module terraform-aws-modules/lambda/aws it by default creates a package for you based on the runtime provided. However, with dotnet, we need to make sure we compile our project after installing dependencies. Luckily the module supports overwriting default commands used for packaging.

Terraform snippet that will restore packages, publish and zip:

1module "dotnet_lambda_function" {
2 source = "terraform-aws-modules/lambda/aws"
4 function_name = "my-dotnet-lambda"
5 description = "My lambda function written in .NET"
6 handler = "My.Dotnet.Lambda::My.Dotnet.Lambda.Function::FunctionHandler"
7 runtime = "dotnet8"
8 source_path = [{
9 path = "../My.Dotnet.Lambda"
10 commands = [
11 "dotnet restore",
12 "dotnet publish -c Release -r linux-arm64 -o publish",
13 "cd ./publish",
14 ":zip"
15 ]
16 }]
17 publish = true
18 architecture = ["arm64"]
20 environment_variables = {
21 ENV = "dev"
22 }
23 attach_policy_statements = true
24 policy_statements = {
25 cloud_watch = {
26 effect = "Allow",
27 actions = ["cloudwatch:PutMetricData"],
28 resources = ["*"]
29 }
30 }
31 tags = {
32 Name = "dotnet-lambda"
33 }

Now you can add policies, IAM role, layers and other resources that your function requires to work after deployment.

Note: make sure you can execute the provided dotnet commands locally without any errors. The Terraform module is written in Python that's why you may see errors thrown by its runtime

© 2024 by Katarzyna Kmiotek. All rights reserved.
Theme by LekoArts