Deploy .Net Core AWS Lambda Function using AWS CodeBuild Pipeline
Tags: lambda, dotnet, devops, aws
Published: 2023-04-11 05:21:48

I have divided the deployment process into 5 steps

1. Understand and update `aws-lambda-tools-defaults.json` of our .Net project
2. Add a `buildspec.yml` file to our .Net project
3. Create an AWS CodeBuild pipeline
4. Permissions required to deploy
5. Run CodeBuild pipeline and deploy our Lambda Function

**Let's begin**

## Step 1: Understand and update aws-lambda-tools-defaults.json of our .Net project

When we create a new .Net Core Lambda Function Project in Visual Studio, a file name `aws-lambda-tools-defaults.json` gets added to our project. You can set build options by using the fields in this file, which the Lambda tooling reads by default.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onbpu552afora5wsu9bc.png)

This is a configuration file to deploy our lambda function.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ngzyhzs0ezz0kv1emm0l.png)

let's update this file to add a few more configurations that we will require for our deployment.

```
{
  "Information": ["All the command line options for the Lambda command can be specified in this file."],
  "profile": "default",
  "region": "eu-west-1",
  "configuration": "Release",
  "function-architecture": "x86_64",
  "function-runtime": "dotnet6",
  "function-memory-size": 256,
  "function-timeout": 30,
  "function-handler": "MyLambdaFunction::MyLambdaFunction.Function::FunctionHandler",
  "function-description": "This is a test lambda function for demo", 
  "s3-bucket": "my-build-source-bucket", 
  "s3-prefix": "MyLambdaFunction-Builds/"
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xeeww0obx5detlovp4eo.png)

**Note:** We have added the below 3 configurations:

1. function-description: Description of our lambda function
2. s3-bucket: S3 bucket name to upload the build output
3. s3-prefix: Folder name inside the above mentioned bucket where build output will be uploaded

## Step 2: Add a buildspec.yml file to our .Net project

> A **buildspec** (build specification) is a collection of build commands and related settings, in YAML format, that **CodeBuild** uses to run a build. If you include a buildspec as part of the source code, by default, the buildspec file must be named buildspec.yml and placed in the root of your source directory.

Right-click on project > Add new item > select a text file > rename to buildspec.yml


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gsxnafhfq0i6mghcjz10.png)

Add the below content to buildspec.yml file

```
version: 0.2
env:
  variables:
  # Set/Override value for below variables using Enviroment Variables of codebuild pipeline 
    LAMBDA_FUNCTION_NAME: "My-AWS-Lambda-Function"
  # Variables specific to this file
    PROJECT_FILE_DIR_PATH: "MyLambdaFunction"
phases:
  install:
    runtime-versions:
      dotnet: 6.0
  build:
    commands:
      - echo Deployment started on `date`for function $LAMBDA_FUNCTION_NAME
      - export PATH="$PATH:/root/.dotnet/tools"
      - dotnet new --install Amazon.Lambda.Templates::*
      - dotnet tool install -g Amazon.Lambda.Tools
      # Change directory to Project(.csproj) file folder
      - cd $PROJECT_FILE_DIR_PATH
      # Build and deploy to lambda function
      - dotnet lambda deploy-function --function-name $LAMBDA_FUNCTION_NAME

```

> **In this build spec declaration:**

> **version** represents the version of the build spec standard being used. This build spec declaration uses the latest version, 0.2.
> **env** Optional sequence. Represents information for one or more custom environment variables.
> **phases** represents the build phases during which you can instruct CodeBuild to run commands. These build phases are listed here as install and build You cannot change the spelling of these build phase names, and you cannot create more build phase names.

After updating `aws-lambda-tools-defaults.json` and adding buildspec.yml file, commit your changes to your source control (GitHub, Bitbucket etc).

That's it, we are now done with the code changes. For the next steps, we will work on AWS console.

## Step 3: Create an AWS CodeBuild pipeline and deploy

Go to AWS console > CodeBuild > click on Build Project

Provide **Project configuration** and **source** repository details (in this example we using **GitHub** as our source provider) :


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ux3qebpttjsnfpmqryi5.png)

Provide Environment details:

> **Note:** Role name will be important, CodeBuild pipeline will use this role to deploy our lambda function


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d19jpscp92aogt8qqyar.png)

Provide the path of **buildspec** file


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mova4siehm8npq3jct5.png)

Leave **Batch configuration**, **Artifacts** & **Logs** section with default settings and click on '**Create build project**'.

## Step 4: Permissions required to deploy:

Make sure your lambda function role should have the below permissions.

For this demo, I have added the below permissions to codebuild role `codebuild-Build-MyLambdaFunction-service-role`.

For Resource, I have kept it for all resources, which you can update as per your requirement.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:GetBucketAcl",
                "s3:GetBucketLocation",
                "s3:GetObjectVersion",
                "lambda:UpdateFunctionCode",
                "lambda:UpdateFunctionConfiguration",
                "lambda:GetFunctionConfiguration"
            ],
            "Resource": "*"
        }
    ]
}

```


## Step 5: Run CodeBuild pipeline and deploy our Lambda Function

So now, our CodeBuild pipeline is ready and we have also added required permissions, let's run the pipeline and test the code build.

Click on our build project and start the build.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e8l5hl0jes7f1l7ek3w7.png)

**What you will see on successful deployment?**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g03k6gbtn87osun5pb9r.png)

Build output logs:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vb9wvyvq0q01gswxtney.png)

Build files uploaded to our S3 bucket:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9nkka5cmc3ozdclhed0k.png)

Lambda function is deployed and function code is updated successfully.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b042wapmngu91sdo6ncb.png)

I hope this article will help you.

Happy learning :)