AWS CDK for Beginners

Rani Lian
Level Up Coding
Published in
8 min readMay 23, 2020

--

AWS CDK Logo

The intended audience for this article is someone who is either new to Amazon Web Services (AWS) or AWS Cloud Development Kit (CDK).

In this article we will learn what AWS CDK is and what it can do for developers interested in automating various aspects of their AWS infrastructure. (hint: if you have the slightest interest in DevOps you will love this framework — trust me).

You may be wondering why AWS and why AWS CDK? In the following sections I will briefly describe the reasons why I choose AWS and AWS CDK for every project I work on.

Brief history of AWS

AWS is the leader in cloud infrastructure as a service. Magic Quadrant ranked it #1 for 9 consecutive years.

AWS releases new services and features every year. AWS publicly launched on March 19, 2006 offering nearly about 2–3 services to the public and fast-forward to today it provides an outstanding number of services for developers to use (In 2020, this number is around 212 according to Wikipedia).

As you can imagine, this makes it very difficult to master all of them. I have actually yet to meet someone that can dive deep on all of the services at a 400 level. Mastering multiple AWS services is quite an accomplishment in itself but unfortunately, is out of scope for this article.

Brief history of AWS CDK

AWS CDK is an open-source framework that allows developers to use their favorite programming language to automate AWS Infrastructure.

One of the many services AWS provides is AWS CloudFormation. AWS CloudFormation allows you to automate your AWS infrastructure using code, termed as Infrastructure as Code (IaC). Put simply, you can use YAML or JSON to describe how you want to configure and deploy your AWS Infrastructure.

Automating your AWS infrastructure this way is fine when you are working alone or have a small set of services that you need to interact with but this can get out of hand really quickly if you have a large team of developers working together which makes it very difficult to maintain and revisit the infrastructure at a later time due to how brittle it can be.

In July 11, 2019 AWS made AWS CDK generally available and the world of infrastructure automation was reinvented.

What is the difference between AWS CDK and AWS CloudFormation?

Both AWS CDK and AWS CloudFormation allow you to automate AWS infrastructure however with AWS CDK you use a programming language (like TypeScript, JavaScript, Python, Java and C#/.NET) to do it while with AWS CloudFormation you use YAML or JSON to do it.

AWS CDK actually generates a YAML AWS CloudFormation template by default from the code you typed before you deploy it. Remember, AWS CDK isn’t a service but instead is an open-source framework that allows developers to use their favorite programming language to configure and deploy their AWS Infrastructure.

AWS CDK makes it easier for developers to work with AWS infrastructure because your AWS infrastructure can now be logically described using familiar programing languages and be completely part of your entire codebase.

Why should I use AWS CDK?

The benefits of AWS CDK are tremendous whether you are a solo developer or a team of developers. You should always be thinking about the Don’t Repeat Yourself (DRY) principle when automating AWS infrastructure, which begins by using AWS CDK.

If the benefits of AWS CDK haven’t jumped at you already allow me to list a few:

  1. You can organize your AWS infrastructure code however it makes sense to you and your team. You want to have one stack that contains all of the AWS infrastructure? Go ahead. Or maybe you want to spin up a stack per developer? Sure thing. Maybe you want to enforce your developers to make sure that all S3 buckets are always private by default. Done deal.
  2. You can utilize the existing team’s skillset in popular programming languages (like Python or TypeScript) to automate AWS infrastructure. You don’t need AWS CloudFormation ‘experts’ anymore when you use AWS CDK.
  3. Type-safety, code-completion, and open-source to the rescue! No need to pull your hair out when something goes wrong; look at the source code, trust the framework, and eliminate common errors when you use AWS CDK.

There are so many benefits of using AWS CDK — I won’t be able to list them all. But it is worth mentioning that with AWS CDK you now have more structured programming language controls to put in place compared to pure SAML or JSON-based approaches. Think what Code Editors can do now when they have access to the source code. Built-in code-completion, documentation, and (for typed languages like TypeScript) code compilation to prevent common user errors.

Take it from someone who has been doing this type of work for a decade. It has truly saved me countless hours automating infrastructure like never before and had made me and my team extremely agile in modifying the infrastructure.

Hello World — in CDK!

The following example is written in TypeScript but feel free to use any other programming language supported by AWS CDK.

In this Hello World example, we will be creating a brand new CDK project which will contain a AWS Lambda function that simply returns “Hello World!” when executed.

Before you begin

  1. Make sure you have created an AWS account.
  2. Make sure you have installed the AWS CLI and have configured the SDK to use an AWS profile. To verify, run aws --version in the terminal.
  3. Make sure you have installed Node.js and the version is greater than 10.3.0. To verify, run node --version in the terminal.
  4. Make sure you have installed AWS CDK CLI. To verify, using the following command
    npm install -g aws-cdk in the terminal.

Create an empty directory

Let’s create an empty directory that will contain our CDK project and navigate to it.

Run the following code in the terminal:mkdir HelloWorldCDK && cd HelloWorldCDK

Create a starter template

We will use the CDK CLI to generate a starter template for TypeScript.

Run the following code in the terminal: cdk init --language typescript

Create a Lambda function

We will create a JavaScript Lambda function that returns “Hello World!” in the response body when executed.

Run the following code in the terminal: mkdir -p functions/helloworld && touch functions/helloworld/index.js

Using your favorite code editor (Note: I prefer using VS Code), paste the following code into functions/helloworld/index.js:

exports.handler = (event, context, callback) => {
callback(null, "Hello World!");
};

Install @aws-cdk/aws-lambda module

The basic project doesn’t include any modules besides the defaults. Since we need to work with AWS Lambda we will need to pull in @aws-cdk/aws-lambda module. Check the API Reference page for a detailed list of all the modules provided for AWS CDK.

Run the following code in the terminal: npm install @aws-cdk/aws-lambda

Deploy the Lambda Function

We created the Lambda function locally and installed the Lambda module but now we need to use AWS CDK to deploy it. In order to do so, we will use the Lambda module to create an instance of a Lambda Function that references the local code we created then we will run CDK deploy to actually deploy it to our AWS account.

Using your favorite code editor, replace lib/hello_world_cdk_lambda_stack.ts with the following code:

import * as cdk from "@aws-cdk/core";
import * as lambda from "@aws-cdk/aws-lambda";
export class HelloWorldCdkLambdaStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// The code that defines your stack goes here
const helloWorldFunction = new lambda.Function(this, "HelloWorldFunction", {
code: lambda.Code.fromAsset("functions/helloworld"),
handler: "index.handler",
runtime: lambda.Runtime.NODEJS_12_X,
description:
"This Lambda Function returns the message: 'Hello World!' in the response body",
});
}
}

Run the following code in the terminal: cdk deploy --profile {AWS_PROFILE} but make sure to replace {AWS_PROFILE} with your AWS Profile.

You should see something like the following:

Example Output
IAM Policy updates

Hit y on the keyboard and press enter. You should then see something like the following:

Deployment Progress & Status updates

What is happening behind the scenes?

When you run cdk deploy the code we placed in lib/hello_world_cdk_lambda_stack.ts is parsed by the CDK Framework which then generates a CloudFormation template located in the cdk.out folder and finally deploys it to CloudFormation.

Our code is pretty simple, all we did was implemented a simple Hello World Lambda function handler and we created an instance of the lambda.Function class that references the Lambda function handler. When we run cdk deploy we notice that AWS CDK is actually deploying more than just the Lambda function. It is also generating an IAM role with Basic Lambda Execution permissions and allowing AWS Lambda to assume it to execute properly.

When does AWS CDK auto-generate additional AWS resources?

If the name of the class you are instantiating starts with Cfn then it is considered a low-level construct otherwise it is considered a high-level construct. Low-Level constructs are usually a one-to-one mapping to raw CloudFormation resources, meaning that they usually only spin up one AWS resource, while High-Level constructs are custom-built classes by the AWS CDK team, open source community, or yourself which perform additional logic such as grouping multiple Low-Level constructs together to simplify a specific task.

In the above example, we use the High-Level construct named lambda.Function which if you look at the source code of this class you can see that it takes care of managing a few dependencies for you like spinning up a basic execution role IAM policy and attaching it to the function.

What’s interesting is that we didn’t have to code any of that ourselves but CDK automatically generates those resources in the CloudFormation template since we are using the High-Level lambda.Function construct in our code.

Run the Lambda function

In your AWS console, navigate to AWS Lambda and you should see that the Lambda function has actually been created.

Click on the Lambda function and Test it (you can provide any request body you like).

You should see that “Hello World!” was returned in the response similar to the following:

Lambda Success Response

Clean up

To delete everything we created, you can either manually delete the CloudFormation stack on the AWS console (but that’s no fun) or use the CDK CLI to do it! Let’s use the CDK CLI to remove them.

Run the following code in the terminal: cdk destroy --profile {AWS_PROFILE} but make sure to replace {AWS_PROFILE} with your AWS Profile.

Conclusion

AWS CDK makes it really easy to automate AWS resources in any way we’d like. In fact, the use of High Level Constructs simplify the work we have to do by generating the necessary dependencies for us.

In the above example, we demonstrated how quick and easy it was to deploy a locally-defined AWS Lambda function through AWS CDK without having to manually create the CloudFormation template.

I hope this article has proved useful to you in highlighting some of the benefits of using AWS CDK. If you have any questions or would like to see more examples like this, reach out to me and let me know!

Thank you for reading!

--

--

Full-Stack Engineer / Senior Technical Consultant. Passionate about reverse-engineering, design thinking, and building things that improve everyday tasks.