.NET 8 Series has started! Join Now for FREE

10 min read

AWS CDK for .NET Developers - Infrastructure As Code To Provision AWS Resources Easily with C#

#dotnet #aws

In this article, we will learn about AWS CDK for .NET Developers to automate the AWS Resource Deployments process. AWS CDK or the AWS Cloud Development Kit is an open-source framework used to provision your AWS Infrastructure resources using familiar programming languages like C#, Python, Node and so. For our use case, we will concentrate on deploying a couple of resources using C# as the language. We will try to automate the deployment of an S3 Bucket, and DynamoDB Table, and just to demonstrate an advanced use case, let’s try to write Infrastructure as Code for AWS Lambda deployment as well.

Have you ever become tired of clicking through AWS Management Console to create, configure and provision new resources to your AWS Account? By the end of this article, you will be able to define your AWS Resources programmatically using C# Lanaguage and deploy resources just by running a deploy command! Let’s get started!

You can check out the source code of this implementation from here.

What is Infrastructure As Code?

Infrastructure as Code (IaC) is a revolutionary approach to managing and provisioning infrastructure resources in a programmatic, code-driven manner. Instead of manually configuring servers, networks, and other components, IaC enables developers and operations teams to define and manage infrastructure through machine-readable scripts. By treating infrastructure as code, organizations can achieve unprecedented levels of agility, scalability, and reliability. With IaC, provisioning and configuring cloud resources becomes automated, repeatable, and version-controlled. It empowers teams to rapidly deploy, modify, and scale their infrastructure, leading to faster time-to-market, reduced human errors, and improved collaboration between development and operations. IaC is the foundation for efficient and consistent cloud infrastructure management in the era of modern software development practices.

AWS CDK for .NET Developers (C#)

AWS CDK is one such IaC framework by AWS. The idea is that you can define your resources in C# and use this CDK to automatically deploy the resources as needed. You don’t have to manually log in to each AWS account, click through and create/configure resources. The CDK C# scripts can be checked in with your source code in your repository. This way, it’s very easy for developers to deploy resources to any stage of your application, like UAT, Test, and even production.

Apart from AWS CDK, there are several other choices in the market. The most popular one is Terraform, about which I will post an article soon. Other options include Pulumi. Of all these only CDK and Pulumi allow you to write your infrastructure as code scripts in C#. You will find AWS CDK very intuitive if you are very sure that you are going to always rely on AWS Infrastructure. Also, unlike Terraform you don’t really need to learn a new scripting language to write code for your Infrastructure. You can simply use C#!

Prerequisites

As usual, here is the list of prerequisites you need before you can get started.

Installing AWS CDK CLI

The AWS CDK CLI is the primary tool to work with the CDK App. Open up your terminal and run the following to globally install the AWS CDK Toolkit.

npm install -g aws-cdk

Bootstrapping AWS for Deployments with CDK

AWS CDK (Cloud Development Kit) bootstrapping is the process of preparing an AWS account to use the AWS CDK framework. Before deploying the CDK stack, you need to bootstrap your AWS environment. Bootstrapping involves setting up an AWS CloudFormation stack that provisions resources required by the CDK, such as an S3 bucket for storing deployment assets, a couple of IAM Roles, and some bucket policies.

To bootstrap, run the following command:

cdk bootstrap

This will create a new Cloudformation stack that includes the required resources, like the S3 bucket and a couple of IAM Roles for granting permissions to the CDK CLI.

aws-cdk-for-dotnet-developers

If you are interested to know what AWS Resources are deployed as part of the CDK Bootstrapping process, please open up AWS Cloudformation, and open the CDKToolkit stack. Here is a screenshot of all the resources deployed as part of the CDK Toolkit stack.

aws-cdk-for-dotnet-developers

Create a .NET CDK Project

Now that the CDK CLI is installed and the required AWS Resources are created, let’s create a new CDK .NET project using the following command.

mkdir cdk-for-dotnet-developers
cd .\cdk-for-dotnet-developers\
cdk init --language csharp

Exploring the CDK Project Structure

Once you have initialized your CDK Project, the new CDK project will be placed under the <directory>/src folder. Open up the Solution file on Visual Studio. Here are the files that come out of the box with this CDK C# project. Let’s examine what each file holds.

aws-cdk-for-dotnet-developers

So, by default, the CDK CLI creates a new stack for us using the project name. In my case, a new empty stack called CdkForDotnetDevelopersStack is created. Now what’s a stack?

An AWS CloudFormation stack is a collection of AWS resources that are created, updated, or deleted as a single unit. It provides a way to define and manage your infrastructure as code.

CloudFormation is an AWS service that allows you to define your infrastructure using a declarative JSON or YAML template. This template describes the desired state of your AWS resources, including EC2 instances, RDS databases, S3 buckets, IAM roles, and more. So, as you can guess, CDK is built on top of AWS CloudFormation giving you your favorite programming language capabilities.

When you create a CloudFormation stack, AWS CloudFormation provisions and configures the resources specified in the template. It handles the necessary steps to create the resources, such as provisioning EC2 instances, creating security groups, configuring load balancers, and setting up IAM policies.

The Default stack in our new CDK Project has no resources defined.

In the Program.cs, we have the following piece of code.

var app = new App();
new CdkForDotnetDevelopersStack(app, "CdkForDotnetDevelopersStack", new StackProps{});
app.Synth();

This is responsible for deploying your CdkForDotnetDevelopersStack stack. `app.Synth()` plays a crucial role in the CDK deployment workflow, enabling the translation of your CDK app code into CloudFormation templates that can be deployed on AWS.

Creating an AWS S3 Bucket using C# with CDK

First up, let’s create a simple and common AWS Resource, which is an S3 Bucket. We will

namespace CdkForDotnetDevelopers
{
public class CdkForDotnetDevelopersStack : Stack
{
internal CdkForDotnetDevelopersStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var s3Bucket = new Bucket(this, "demobucket", new BucketProps
{
Versioned = false,
AutoDeleteObjects = true,
RemovalPolicy = RemovalPolicy.DESTROY
});
new CfnOutput(this, "BucketArn", new CfnOutputProps { Value = s3Bucket.BucketArn });
}
}
}

Here, in Line #7, the `new Bucket` is a CDK Construct. Constructs are the basic building blocks of AWS CDK apps. A construct represents a “cloud component” and encapsulates everything AWS CloudFormation needs to create the component. Apart from that, we can define various properties of our new bucket, like some removal policies and stuff.

In-Line #14, we are printing out the ARN of the newly created AWS S3 Bucket.

With all these changes done, run the following to deploy the stack.

cdk deploy

Once you run the deploy command, you will be able to see the changesets created on AWS CloudFormation.

aws-cdk-for-dotnet-developers

And in a couple of seconds, the new S3 bucket will be created for you. Also, the newly created bucket’s ARN will also be printed once the provisioning is completed, as you can see in the below screenshot.

aws-cdk-for-dotnet-developers

If you navigate to AWS CloudFormation, you can see that our new stack has been created. Click on the Stack.

aws-cdk-for-dotnet-developers

As you see, these are the resources provisioned as part of the CDK Deploy process.

aws-cdk-for-dotnet-developers

You can also navigate to AWS S3 to confirm if the bucket has been created.

aws-cdk-for-dotnet-developers

What if I wanted to change a resource configuration? For example, I want to enable Versioning in the S3 Bucket. I would simply go to my CDK Code and set the Versioned props of my bucket resource to true. With that done, to see the changes, you can simply run the `cdk diff` command. This would give you the delta of the changes that are between your CDK code and your actual CloudFormation Stack.

As you can see, the below screenshot shows the delta, which is pointing to the VersioningConfiguration. You can simply run the `cdk deploy` command to provision these changes.

aws-cdk-for-dotnet-developers

If you are new to AWS S3 concepts, I have written an article targeting AWS S3 for .NET Developers where we will learn about managing S3 Buckets, uploading, deleting, and downloading objects from the bucket and so much more. Here is a link to the article.

Creating an AWS DynamoDB Table using C# with CDK

Let’s go through another simple example, creating a new AWS DynamoDB table with the CDK Project. Open up your code, and add in the following.

var ddbTable = new Table(this, "product-table", new TableProps
{
TableName = "products",
PartitionKey = new Attribute { Name = "id", Type = AttributeType.STRING },
BillingMode = BillingMode.PAY_PER_REQUEST
});
new CfnOutput(this, "TableArn", new CfnOutputProps { Value = ddbTable.TableArn });

Add the above code soon after the S3 bucket creation code. As you can see, we have defined the DynamoDb Tablename as products, and have added a partition key named Id, which is a string. Let’s deploy this using the `cdk deploy` command.

aws-cdk-for-dotnet-developers

I had written an entire article about implementing CRUD Operations in ASP.NET Core WebAPI with AWS DynamoDB. To get a better understanding of this AWS Managed NoSQL Database service, do read the article.

Deploying an AWS Lambda using C# with CDK

First up, let’s actually create a new Lambda Project. In the existing C# Solution File, I will add a new Lambda Project.

aws-cdk-for-dotnet-developers

Since this is just to demonstrate the Lambda deployment using AWS CDK, we will not be adding any extra changes to the Lambda. Let’s keep it simple. At the root of the Lambda Project, run the following command to generate the .zip file.

dotnet lambda package --configuration release --framework net6.0 --output-package releases/test.zip

aws-cdk-for-dotnet-developers

This should spit out a zip file under the releases folder.

aws-cdk-for-dotnet-developers

The idea is to use this zip file location in our CDK code and deploy the Lambda. Let’s see what the code looks like. Open up the CDK Project and edit the code, and add in the following.

var lambdaFunction = new Function(this, "test-function", new FunctionProps
{
Runtime = Runtime.DOTNET_6,
Code = Code.FromAsset("./src/TestLambda/releases/test.zip"),
Handler = "TestLambda::TestLambda.Function::FunctionHandler"
});

That’s it! The code gets the zip file and uploads the Lambda to AWS along with the mentioned configuration. You can also define other properties such as memory size, log retention, and so on. Run the CDK Deploy command, and here is the new Lambda that was uploaded. How simple is this?

aws-cdk-for-dotnet-developers

To learn more about AWS Lambda for .NET Developers, you can refer to this article.

Destroy

It’s important to delete/destroy the AWS resources/stack once you are done testing. Else it might incur additional costs to your AWS account. To delete the entire stack, you can run the following command. Note that you will have to run this command from the directory wherever cdk.json exists.

cdk destroy

aws-cdk-for-dotnet-developers

This will delete all the resources associated with your stack. As simple as that!

That’s a wrap for this article. Hope you liked it. Do you want to see some advanced Resource Deployments to AWS using CDK & C#? Do let me know in the comments section below!

Summary

In this quick guide, we got started with AWS CDK for .NET Developers. We covered basics like what Infrastructure as Code means, and how AWS CDK helps you write Infrastructure code using C#. We also learned about the implementation, like installing the CDK CLI on our machine, initializing a new CDK C# project, and understanding the CDK project structure. Finally, we learned about the AWS CloudFormation stack, deploying an S3 bucket, DynamoDb Table, and also deploying an AWS Lambda using the dotnet-generated zip file.

You can check out the source code of this implementation from here.

Make sure to share this article with your colleagues if it helped you! Helps me get more eyes on my blog as well. Thanks!

Stay Tuned. You can follow this newsletter to get notifications when I publish new articles – https://newsletter.codewithmukesh.com. Do share this article with your colleagues and dev circles if you found this interesting. Thanks!

Source Code ✌️
Grab the source code of the entire implementation by clicking here. Do Follow me on GitHub .
Support ❤️
If you have enjoyed my content and code, do support me by buying a couple of coffees. This will enable me to dedicate more time to research and create new content. Cheers!
Share this Article
Share this article with your network to help others!
What's your Feedback?
Do let me know your thoughts around this article.

Boost your .NET Skills

I am starting a .NET 8 Zero to Hero Series soon! Join the waitlist.

Join Now

No spam ever, we are care about the protection of your data. Read our Privacy Policy