Beginner Guide to Setting up CDK

The DevOps Geek
7 min readMar 16, 2023

--

If you are looking to get started with the AWS Cloud Development Kit (CDK) using TypeScript, this blog post will guide you through the process of setting up your development environment and creating your first CDK application.

What is CDK?

The AWS CDK is an open-source software development framework that enables you to define cloud infrastructure using familiar programming languages such as TypeScript, JavaScript, Python, Java, and C#. It allows developers to leverage the full power of programming languages to define, manage, and deploy cloud infrastructure as code.

Why CDK?

Improved developer productivity

The AWS CDK allows developers to use familiar programming languages and tools to define cloud infrastructure. This reduces the learning curve associated with learning new configuration languages and tools. It also makes it easier for developers to collaborate on infrastructure code as they can use the same programming language and tools they use for their application code.

Higher-level abstraction

The AWS CDK provides a higher-level of abstraction for defining cloud infrastructure. This allows developers to focus on defining the desired state of their infrastructure without worrying about the implementation details. This abstraction also helps reduce the risk of human error and makes it easier to maintain infrastructure code over time.

Improved maintainability

Infrastructure-as-code (IaC) should be treated like any other codebase, and as such, should be easy to read, understand, and maintain. The AWS CDK allows developers to define infrastructure using familiar programming languages and tools, making it easier to understand and maintain over time.

Consistency

The AWS CDK makes it easy to define infrastructure in a consistent manner, reducing the risk of inconsistencies that can cause problems during deployment. This consistency helps ensure that infrastructure is deployed and configured in the same way every time, reducing the risk of issues and making it easier to troubleshoot issues that do arise.

Automation

The AWS CDK enables you to automate the deployment of infrastructure as code, making it possible to define and deploy infrastructure programmatically. This automation reduces the risk of human error and helps ensure that infrastructure is deployed consistently and reliably.

Prerequisites

Before you start using CDK with TypeScript, you will need to have the following installed on your system:

  • Node.js (version 10.3.0 or later)
  • npm (version 6.14.0 or later)

You can download and install Node.js and npm from the official website: https://nodejs.org/en/download/.

You will also need to have aws sdk installed and configured using

aws configure

Install the CDK CLI

Once you have installed Node.js and npm, you can install the CDK CLI globally on your system using the following command:

npm install -g aws-cdk

Create a New CDK Project

CDK needs to be in an empty directory. The name of the CDK stack will be based on the directory name. CDK init won’t run if the directory is not empty.

mkdir mycdktutorial
cd mycdktutorial

cdk init app --language=typescript

This will create a new CDK application in the current directory using TypeScript as the programming language.

Project Structure

Here is a typical project structure for a CDK application in TypeScript:

.
├── bin # Entry point of the CDK application
│ └── <app>.ts
├── lib # Definition of CDK stacks and constructs
│ └── <stack>.ts
├── test # Unit tests for CDK stacks and constructs
│ └── <stack>.test.ts
├── cdk.json # Configuration settings for the CDK application
├── package.json # Dependencies for the CDK application
├── tsconfig.json # TypeScript configuration settings for the CDK application
├── README.md # Documentation for the CDK application
└── .gitignore # Files and directories to ignore when committing changes
# to the CDK application

The bin directory contains the entry point of the CDK application. In TypeScript, this is typically a file called <app>.ts. The entry point creates an instance of the cdk.App class and initializes the stack(s) that you want to deploy.

The lib directory contains the CDK stack(s) that define the infrastructure resources that you want to deploy. In TypeScript, each stack is typically defined in a file called <stack>.ts. The CDK stack is defined using the AWS CDK API and includes AWS resources such as Amazon S3 buckets, Amazon EC2 instances, Amazon RDS instances, and more.

The test directory contains unit tests for the CDK stack(s). In TypeScript, each test file typically tests a single stack and is named <stack>.test.ts.

The cdk.json file contains configuration settings for the CDK application, such as the AWS region and account ID.

The package.json file contains the dependencies for the CDK application and any scripts that you want to use for building, testing, or deploying your application.

The tsconfig.json file contains the TypeScript configuration settings for the CDK application.

The README.md file contains instructions on how to use the CDK application and any relevant information about the application.

The .gitignore file specifies the files and directories that should be ignored by Git when committing changes to the CDK application.

Bootstrap

One of the first steps in using the CDK is to bootstrap your AWS environment, which initializes the resources required for deploying CDK stacks. To bootstrap your AWS environment using the CDK, run the following command:

cdk bootstrap aws://<AWS account ID>/<AWS region>

When you run the cdk bootstrap command, it creates an Amazon S3 bucket and an AWS CloudFormation stack called CDKToolkit in your specified region. The CDKToolkit stack contains a set of resources required by the CDK to operate, including an IAM role that grants permissions to the CDK to manage resources on your behalf.

Sample code

This code is a simple example of how to define an Amazon SQS queue resource in an AWS CDK stack using TypeScript. It comes pre-packaged when you run cdk init but commented out. Simply uncomment it to run it.

// Import the required CDK and SQS modules
import * as cdk from 'aws-cdk-lib';
import * as sqs from 'aws-cdk-lib/aws-sqs';

// Define a new class that extends the CDK Stack class
export class <app>Stack extends cdk.Stack {

// Define the constructor function for the class
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {

// Call the parent constructor with the specified scope, ID, and properties
super(scope, id, props);

// Define your stack's resources here

// Create a new Amazon SQS queue with the specified name and visibility timeout
const queue = new sqs.Queue(this, '<app>Queue', {
visibilityTimeout: cdk.Duration.seconds(300) // Set the visibility timeout of the queue to 300 seconds
});
}
}

Build the CDK Application

Once you have written your infrastructure code, you need to build your CDK application using the following command:

npm run build

This will compile your TypeScript code into JavaScript code that can be executed by Node.js.

Test

With typescript you can also add unit tests in the test folder. Here’s an example, replace <app> with your app name:

import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import * as <app> from '../lib/<app>-stack';// example test. To run these tests, uncomment this file along with the
// example resource in lib/timeline_website_cdk-stack.ts
test('SQS Queue Created', () => {
const app = new cdk.App();
// // WHEN
const stack = new <app>.<app>Stack(app, 'MyTestStack');
// // THEN
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::SQS::Queue', {
VisibilityTimeout: 300
// });
});

Deploy the Infrastructure

To deploy your infrastructure to the AWS Cloud, run the following command:

cdk deploy

This will deploy your infrastructure resources to your AWS account and will show the following output. You can see in the output than SQS queue was successfully created. You can visit the AWS console SQS to see the new resource or the cloudformation UI to find the ARN of the SQS resource.

MyCdkStack | 0/3 | 13:16:50 | REVIEW_IN_PROGRESS   | AWS::CloudFormation::Stack | MyCdkStack User Initiated
MyCdkStack | 0/3 | 13:16:56 | CREATE_IN_PROGRESS | AWS::CloudFormation::Stack | MyCdkStack User Initiated
MyCdkStack | 0/3 | 13:16:59 | CREATE_IN_PROGRESS | AWS::SQS::Queue | MyCdkQueue
MyCdkStack | 0/3 | 13:16:59 | CREATE_IN_PROGRESS | AWS::CDK::Metadata | CDKMetadata/Default (CDKMetadata)
MyCdkStack | 0/3 | 13:17:01 | CREATE_IN_PROGRESS | AWS::CDK::Metadata | CDKMetadata/Default (CDKMetadata) Resource creation Initiated
MyCdkStack | 1/3 | 13:17:01 | CREATE_COMPLETE | AWS::CDK::Metadata | CDKMetadata/Default (CDKMetadata)
MyCdkStack | 1/3 | 13:17:01 | CREATE_IN_PROGRESS | AWS::SQS::Queue | MyCdkQueue Resource creation Initiated
1/3 Currently in progress: MyCdkStack, MyCdkQueue
MyCdkStack | 2/3 | 13:18:12 | CREATE_COMPLETE | AWS::SQS::Queue | MyCdkQueue
MyCdkStack | 3/3 | 13:18:13 | CREATE_COMPLETE | AWS::CloudFormation::Stack | MyCdkStack

✅ MyCdkStack

✨ Deployment time: 86.59s

Stack ARN:
arn:aws:cloudformation:na-west-2:123456789012:stack/MyCdkStack/cf...

✨ Total time: 94.75s

Clean Up

When you are finished working with your CDK application, you can delete the resources that were created by running the following command:

cdk destroy

This will delete all the resources that were created by the CDK deployment.

Let me know your thoughts!

Please feel free to leave a comment below, sharing your experiences, insights, or questions. Engaging in discussions helps us all grow and learn from one another.

If you found this blog post helpful and informative, please show your support by clicking the clap button below. Your appreciation motivates me to continue creating content that benefits our community of software engineers and DevOps enthusiasts.

Also, don’t forget to follow my Medium profile to stay updated on the latest blog posts, tips, and resources related to DevOps, software development, and technology in general. Together, let’s continue learning and growing in this ever-evolving field. Happy reading!

References

  1. AWS CDK Developer Guide: Provides comprehensive documentation and examples on how to use the AWS CDK framework, including getting started guides, best practices, and reference material.
  2. CDK Workshop: A hands-on guide that walks you through creating CDK applications using TypeScript, including setting up your development environment, defining infrastructure resources, and deploying to the AWS Cloud.
  3. CDK API Reference: A complete reference of the AWS CDK API, including all available AWS resource constructs and associated properties.
  4. AWS CDK Samples: A repository of sample code for various AWS CDK use cases, including examples using TypeScript, Python, and Java.
  5. AWS CDK GitHub Repository: The official GitHub repository for the AWS CDK, where you can find the latest release notes, bug reports, and contribute to the development of the framework.
  6. TypeScript Documentation: Comprehensive documentation and examples on how to use TypeScript, including language features, syntax, and best practices.
  7. Node.js Documentation: Official documentation for Node.js, including guides, APIs, and examples.
  8. NPM Documentation: Comprehensive documentation and examples on how to use npm, including package management, scripts, and CLI commands.

--

--

The DevOps Geek

I'm a tech enthusiast with 10+ years of experience in software development, sharing practical insights on DevOps. All posts are generated with help from AI