Create & Deploy a Hello World .NET Core 3.1 AWS Lambda Function using Only the .NET Core CLI

Well, the title sums it all! Let’s see how to do that.

Step 1 — Install .NET Core CLI

Download & install .NET Core 3.1 from dotnet.microsoft.com/download. Verify the installation:

> dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.301
 Commit:    7feb845744

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.15
 OS Platform: Darwin
 RID:         osx.10.15-x64
 Base Path:   /usr/local/share/dotnet/sdk/3.1.301/

Host (useful for support):
  Version: 3.1.5
  Commit:  65cd789777

.NET Core SDKs installed:
  3.1.200 [/usr/local/share/dotnet/sdk]
  3.1.300 [/usr/local/share/dotnet/sdk]
  3.1.301 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.App 3.1.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.4 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.5 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.16 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.2 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.4 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.5 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Step 2 — Install Lambda Templates

Install the Amazon.Lambda.Templates NuGet package so you can create a Lambda function using one of the predefined templates for AWS Lambda:

dotnet new --install Amazon.Lambda.Templates

That command installs the following templates:

Templates                                                 Short Name                                        Language          Tags                                 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
Order Flowers Chatbot Tutorial                            lambda.OrderFlowersChatbot                        [C#]              AWS/Lambda/Function                  
Lambda Custom Runtime Function (.NET Core 3.1)            lambda.CustomRuntimeFunction                      [C#], F#          AWS/Lambda/Function                  
Lambda Detect Image Labels                                lambda.DetectImageLabels                          [C#], F#          AWS/Lambda/Function                  
Lambda Empty Function                                     lambda.EmptyFunction                              [C#], F#          AWS/Lambda/Function                  
Lex Book Trip Sample                                      lambda.LexBookTripSample                          [C#]              AWS/Lambda/Function                  
Lambda Simple Application Load Balancer Function          lambda.SimpleApplicationLoadBalancerFunction      [C#]              AWS/Lambda/Function                  
Lambda Simple DynamoDB Function                           lambda.DynamoDB                                   [C#], F#          AWS/Lambda/Function                  
Lambda Simple Kinesis Firehose Function                   lambda.KinesisFirehose                            [C#]              AWS/Lambda/Function                  
Lambda Simple Kinesis Function                            lambda.Kinesis                                    [C#], F#          AWS/Lambda/Function                  
Lambda Simple S3 Function                                 lambda.S3                                         [C#], F#          AWS/Lambda/Function                  
Lambda Simple SNS Function                                lambda.SNS                                        [C#]              AWS/Lambda/Function                  
Lambda Simple SQS Function                                lambda.SQS                                        [C#]              AWS/Lambda/Function                  
Lambda ASP.NET Core Web API                               serverless.AspNetCoreWebAPI                       [C#], F#          AWS/Lambda/Serverless                
Lambda ASP.NET Core Web Application with Razor Pages      serverless.AspNetCoreWebApp                       [C#]              AWS/Lambda/Serverless                
Serverless Detect Image Labels                            serverless.DetectImageLabels                      [C#], F#          AWS/Lambda/Serverless                
Lambda DynamoDB Blog API                                  serverless.DynamoDBBlogAPI                        [C#]              AWS/Lambda/Serverless                
Lambda Empty Serverless                                   serverless.EmptyServerless                        [C#], F#          AWS/Lambda/Serverless                
Lambda Giraffe Web App                                    serverless.Giraffe                                F#                AWS/Lambda/Serverless                
Serverless Simple S3 Function                             serverless.S3                                     [C#], F#          AWS/Lambda/Serverless                
Step Functions Hello World                                serverless.StepFunctionsHelloWorld                [C#], F#          AWS/Lambda/Serverless                
Serverless WebSocket API                                  serverless.WebSocketAPI                           [C#]              AWS/Lambda/Serverless                
Console Application                                       console                                           [C#], F#, VB      Common/Console                       
Class library                                             classlib                                          [C#], F#, VB      Common/Library                       
WPF Application                                           wpf                                               [C#]              Common/WPF                           
WPF Class library                                         wpflib                                            [C#]              Common/WPF                           
WPF Custom Control Library                                wpfcustomcontrollib                               [C#]              Common/WPF                           
WPF User Control Library                                  wpfusercontrollib                                 [C#]              Common/WPF                           
Windows Forms (WinForms) Application                      winforms                                          [C#]              Common/WinForms                      
Windows Forms (WinForms) Class library                    winformslib                                       [C#]              Common/WinForms                      
Worker Service                                            worker                                            [C#]              Common/Worker/Web                    
Unit Test Project                                         mstest                                            [C#], F#, VB      Test/MSTest                          
NUnit 3 Test Project                                      nunit                                             [C#], F#, VB      Test/NUnit                           
NUnit 3 Test Item                                         nunit-test                                        [C#], F#, VB      Test/NUnit                           
xUnit Test Project                                        xunit                                             [C#], F#, VB      Test/xUnit                           
Razor Component                                           razorcomponent                                    [C#]              Web/ASP.NET                          
Razor Page                                                page                                              [C#]              Web/ASP.NET                          
MVC ViewImports                                           viewimports                                       [C#]              Web/ASP.NET                          
MVC ViewStart                                             viewstart                                         [C#]              Web/ASP.NET                          
Blazor Server App                                         blazorserver                                      [C#]              Web/Blazor                           
Blazor WebAssembly App                                    blazorwasm                                        [C#]              Web/Blazor/WebAssembly               
ASP.NET Core Empty                                        web                                               [C#], F#          Web/Empty                            
ASP.NET Core Web App (Model-View-Controller)              mvc                                               [C#], F#          Web/MVC                              
ASP.NET Core Web App                                      webapp                                            [C#]              Web/MVC/Razor Pages                  
ASP.NET Core with Angular                                 angular                                           [C#]              Web/MVC/SPA                          
ASP.NET Core with React.js                                react                                             [C#]              Web/MVC/SPA                          
ASP.NET Core with React.js and Redux                      reactredux                                        [C#]              Web/MVC/SPA                          
Razor Class Library                                       razorclasslib                                     [C#]              Web/Razor/Library/Razor Class Library
ASP.NET Core Web API                                      webapi                                            [C#], F#          Web/WebAPI                           
ASP.NET Core gRPC Service                                 grpc                                              [C#]              Web/gRPC                             
dotnet gitignore file                                     gitignore                                                           Config                               
global.json file                                          globaljson                                                          Config                               
NuGet Config                                              nugetconfig                                                         Config                               
Dotnet local tool manifest file                           tool-manifest                                                       Config                               
Web Config                                                webconfig                                                           Config                               
Solution File                                             sln                                                                 Solution                             
Protocol Buffer File                                      proto                                                               Web/gRPC                             

Step 3 — Examine a Template

Examine the lambda.EmptyFunction template:

> dotnet new lambda.EmptyFunction --help
Usage: new [options]

Options:
  -h, --help          Displays help for this command.
  -l, --list          Lists templates containing the specified name. If no name is specified, lists all templates.
  -n, --name          The name for the output being created. If no name is specified, the name of the current directory is used.
  -o, --output        Location to place the generated output.
  -i, --install       Installs a source or a template pack.
  -u, --uninstall     Uninstalls a source or a template pack.
  --nuget-source      Specifies a NuGet source to use during install.
  --type              Filters templates based on available types. Predefined values are "project", "item" or "other".
  --dry-run           Displays a summary of what would happen if the given command line were run if it would result in a template creation.
  --force             Forces content to be generated even if it would change existing files.
  -lang, --language   Filters templates based on language and specifies the language of the template to create.
  --update-check      Check the currently installed template packs for updates.
  --update-apply      Check the currently installed template packs for update, and install the updates.


Lambda Empty Function (C#)
Author: AWS
Options:                                                                                                                                    
  -p|--profile  The AWS credentials profile set in aws-lambda-tools-defaults.json and used as the default profile when interacting with AWS.
                string - Optional                                                                                                           

  -r|--region   The AWS region set in aws-lambda-tools-defaults.json and used as the default region when interacting with AWS.              
                string - Optional

Step 4 — Create Lambda Function

Create a function project with the lambda.EmptyFunction template:

> dotnet new lambda.EmptyFunction --name MyFunction
The template "Lambda Empty Function" was created successfully.

Take a look at what was created:

> tree MyFunction 
MyFunction
├── src
│   └── MyFunction
│       ├── Function.cs
│       ├── MyFunction.csproj
│       ├── Readme.md
│       └── aws-lambda-tools-defaults.json
└── test
    └── MyFunction.Tests
        ├── FunctionTest.cs
        └── MyFunction.Tests.csproj

4 directories, 6 files

Step 5 — Install .NET Core Global Tool

Install the Amazon.Lambda.Tools .NET Core Global Tool to build & deploy the function. If it’s already installed, update it:

> dotnet tool install -g Amazon.Lambda.Tools
Tool 'amazon.lambda.tools' is already installed.
> dotnet tool update -g Amazon.Lambda.Tools
Tool 'amazon.lambda.tools' was reinstalled with the latest stable version (version '4.0.0').

Step 6 — Deploy the Function

> cd MyFunction/src/MyFunction
> dotnet lambda deploy-function MyFunction --profile <AWS CLI profile>
Amazon Lambda Tools for .NET Core applications (4.0.0)
Project Home: https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet
	
Enter AWS Region: (The region to connect to AWS services, if not set region will be detected from the environment.)
us-east-1
Executing publish command
Deleted previous publish folder
... invoking 'dotnet publish', working folder '/Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/publish'
... publish: Microsoft (R) Build Engine version 16.6.0+5ff7b0c9e for .NET Core
... publish: Copyright (C) Microsoft Corporation. All rights reserved.
... publish:   Determining projects to restore...
... publish:   All projects are up-to-date for restore.
... publish:   MyFunction -> /Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/linux-x64/MyFunction.dll
... publish:   MyFunction -> /Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/publish/
Changed permissions on published file (chmod +rx Amazon.Lambda.Serialization.SystemTextJson.dll).
Changed permissions on published file (chmod +rx MyFunction.dll).
Changed permissions on published file (chmod +rx MyFunction.deps.json).
Changed permissions on published file (chmod +rx Amazon.Lambda.Core.dll).
Changed permissions on published file (chmod +rx MyFunction.pdb).
Changed permissions on published file (chmod +rx MyFunction.runtimeconfig.json).
Zipping publish folder /Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/publish to /Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/MyFunction.zip
... zipping:   adding: Amazon.Lambda.Serialization.SystemTextJson.dll (deflated 46%)
... zipping:   adding: MyFunction.dll (deflated 56%)
... zipping:   adding: MyFunction.deps.json (deflated 68%)
... zipping:   adding: Amazon.Lambda.Core.dll (deflated 46%)
... zipping:   adding: MyFunction.pdb (deflated 24%)
... zipping:   adding: MyFunction.runtimeconfig.json (deflated 23%)
Created publish archive (/Users/harishkm/Downloads/MyFunction/src/MyFunction/bin/Release/netcoreapp3.1/MyFunction.zip).
Creating new Lambda function MyFunction
Select IAM Role that to provide AWS credentials to your code:
    1) *** Create new IAM Role ***
1
Enter name of the new IAM Role:
MyFunction-role
Select IAM Policy to attach to the new role and grant permissions
    1) AWSLambdaFullAccess (Provides full access to Lambda, S3, DynamoDB, CloudWatch Metrics and  ...)
    2) AWSLambdaReplicator
    3) AWSLambdaDynamoDBExecutionRole (Provides list and read access to DynamoDB streams and writ ...)
    4) AWSLambdaExecute (Provides Put, Get access to S3 and full access to CloudWatch Logs.)
    5) AWSLambdaSQSQueueExecutionRole (Provides receive message, delete message, and read attribu ...)
    6) AWSLambdaKinesisExecutionRole (Provides list and read access to Kinesis streams and write  ...)
    7) AWSLambdaReadOnlyAccess (Provides read only access to Lambda, S3, DynamoDB, CloudWatch Met ...)
    8) AWSLambdaBasicExecutionRole (Provides write permissions to CloudWatch Logs.)
    9) AWSLambdaInvocation-DynamoDB (Provides read access to DynamoDB Streams.)
   10) AWSLambdaVPCAccessExecutionRole (Provides minimum permissions for a Lambda function to exe ...)
   11) AWSLambdaRole (Default policy for AWS Lambda service role.)
   12) AWSLambdaENIManagementAccess (Provides minimum permissions for a Lambda function to manage ...)
   13) *** No policy, add permissions later ***
8
Waiting for new IAM Role to propagate to AWS regions
...............	 Done
New Lambda function created

Step 7 — Invoke the Function

> dotnet lambda invoke-function MyFunction --payload "Hello World" --profile <AWS CLI profile>
Amazon Lambda Tools for .NET Core applications (4.0.0)
Project Home: https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet
	
Enter AWS Region: (The region to connect to AWS services, if not set region will be detected from the environment.)
us-east-1
Payload:
"HELLO WORLD"

Log Tail:
START RequestId: daf60447-e3d0-43e2-82bb-a8a953ce9833 Version: $LATEST
END RequestId: daf60447-e3d0-43e2-82bb-a8a953ce9833
REPORT RequestId: daf60447-e3d0-43e2-82bb-a8a953ce9833	Duration: 174.95 ms	Billed Duration: 200 ms	Memory Size: 256 MB	Max Memory Used: 69 MB