What is AWS CDK?

What is AWS CDK?

Imagine you're a developer needing to set up a bunch of AWS resources for your new project. Instead of manually configuring everything through the AWS console, you can use the AWS Cloud Development Kit (AWS CDK). This toolkit lets you write code in your favorite programming languages like TypeScript, JavaScript, Python, Java, or C# to automate the process.

For example, think of it as creating a blueprint for a house. Instead of physically building each part yourself, you design it all on your computer. The AWS CDK works similarly—it lets you write code that defines all the cloud resources you need. Once you're done, the CDK translates your code into AWS CloudFormation templates, which then handle the actual creation of your resources.

So, if you’re familiar with AWS CloudFormation, using the AWS CDK will feel like an upgrade. You’ll still be building the same cloud infrastructure, but now you’ll be doing it more efficiently with the added flexibility and convenience of using programming languages you’re already comfortable with.

What is Infra as a Code?  

In simple terms, using code, you describe the infrastructure you want to deploy in a model that can be easily understood. Much like application code, this infrastructure code becomes part of your project.Imagine you've built a web application. This application needs to be hosted somewhere to be accessible. With Infrastructure as Code (IaC), you can define exactly where this infrastructure will be deployed, such as a public cloud provider like Microsoft Azure, Amazon AWS, or Google Cloud. You can also specify what type of service your web application will run on, such as an Azure Web App or an AWS S3 bucket. Additionally, you can configure settings for the web app, including EC2 Instance type, network security, and the domain name for your application, among other things.

Reasons to Use AWS CDK

1. You can spin up cloud infrastructure using TypeScript! How cool is that?

2. Code reuse is a breeze. This is a lifesaver when you're setting up multiple environments or applications.

3. The AWS CDK is like a seasoned guide, built with best practices in mind. While it won't guarantee perfection, it certainly nudges you in the right direction.

4. You can commit your code and use the AWS CDK as Infrastructure as Code (IaC). Every change gets documented in source control, so you can track your progress just like you do with your application code.

5. You get to write less and do more compared to using CloudFormation. Who doesn’t love efficiency?

Installation & Get Started with AWS CDK

Hopefully, you have a node installed in your system.

npm install -g aws-cdk

Go to your directory and run

cdk init app --language=typescript 

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

To start using the CDK, you need to bootstrap your AWS environment, which sets up the necessary resources for deploying CDK stacks. Run this command:

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

This command creates an S3 bucket and a CloudFormation stack named CDKToolkit in your specified region, including an IAM role with the permissions needed for the CDK to manage resources.

Here’s a simple example of defining an Amazon SQS queue resource in an AWS CDK stack using TypeScript. It’s included in the CDK package. 

import * as cdk from 'aws-cdk-lib';
import * as sqs from 'aws-cdk-lib/aws-sqs';

export class MyCdkStack extends cdk.Stack {

  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
	super(scope, id, props);
	// Define your stack's resources here

	const queue = new sqs.Queue(this, 'MyCdkQueue', {
  	 visibilityTimeout: cdk.Duration.seconds(300) 	
     });
  }
}

Defining Infrastructure with CDK 

What are constructs?

Constructs are the fundamental components of AWS CDK applications. Constructs are reusable cloud components representing AWS resources or groups of resources, such as defining single resources like S3, Workers, monitoring tools, or a group of them to build an app using combinations of such services.

For example, if you’re setting up a system that needs to analyze documents, you can use constructs to define and manage the AWS resources required to perform tasks such as document storage and processing. To learn more about leveraging AWS services for tasks like these, check out how to Analyze Documents Using AWS Services.

What is Stacks 

Is the smallest physical unit of deployment, and maps directly onto a CloudFormation Stack

“Hello World” and deployment with the AWS CDK 

We'll create a stack that includes multiple AWS services: an S3 bucket for storage, a Lambda function to process data, and an API Gateway to expose an HTTP endpoint.

Initialize cdk

mkdir hello-cdk
cd hello-cdk
cdk init app --language typescript

bin/hello-world-cdk.ts

#!/usr/bin/env node
import "source-map-support/register";
import * as cdk from "aws-cdk-lib";
import { HelloCdkStack as HelloWorldCdkStack } from "../lib/hello-world-cdk-stack";

const app = new cdk.App();
new HelloWorldCdkStack(app, "HelloWorldCdkStack", {

 env: {
   account: "YourAccountID",
   region: "ap-south-1",
 },

});

lib/hello-world-cdk-stack.ts

import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as apigateway from "aws-cdk-lib/aws-apigateway";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as lambda from "aws-cdk-lib/aws-lambda";

export class HelloCdkStack extends cdk.Stack {
 constructor(scope: Construct, id: string, props?: cdk.StackProps) {
   super(scope, id, props);

   // Create an S3 bucket
   const bucket = new s3.Bucket(this, "MyBucket", {
     versioned: true,
     removalPolicy: cdk.RemovalPolicy.DESTROY, // NOT recommended for production code
     autoDeleteObjects: true, // NOT recommended for production code
   });

   // Create a Lambda function
   const lambdaFunction = new lambda.Function(this, "MyLambdaFunction", {
     runtime: lambda.Runtime.NODEJS_18_X,
     handler: "index.handler",
     code: lambda.Code.fromAsset("lambda"),
     environment: {
       BUCKET_NAME: bucket.bucketName,
     },
   });



   bucket.grantReadWrite(lambdaFunction);

   const api = new apigateway.RestApi(this, "MyApi", {
     restApiName: "My Service",
     description: "This service serves a simple example.",
   });

   const getIntegration = new apigateway.LambdaIntegration(lambdaFunction, {
     requestTemplates: { "application/json": '{ "statusCode": "200" }' },
   });

   const resource = api.root.addResource("hello");
   resource.addMethod("GET", getIntegration);
 }
}

/lambda/index.js

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

exports.handler = async (event) => {
 const bucketName = process.env.BUCKET_NAME;
 const key = 'hello.txt';
 const params = {
   Bucket: bucketName,
   Key: key,
   Body: 'Hello, CDK!',
 };

 await s3.putObject(params).promise();

 return {
   statusCode: 200,
   body: JSON.stringify({
     message: 'Hello, World!',
   }),
 };
};

Suggested Reads- Streaming Videos With AWS Elastic Transcoder

Conclusion

In conclusion, the AWS Cloud Development Kit (CDK) offers a powerful, flexible, and efficient way to define cloud infrastructure using familiar programming languages. By leveraging CDK, developers can take advantage of high-level constructs, reusable components, and best practices to streamline the creation and management of AWS resources. 

Whether you're new to cloud development or an experienced architect, CDK's code-centric approach empowers you to build, deploy, and manage infrastructure with greater ease and precision. As the cloud landscape continues to evolve, taking advantage of tools like CDK will be essential in driving innovation and maintaining agility in your cloud projects.

Happy coding!

Frequently Asked Questions

What is AWS CDK and how does it differ from CloudFormation?

AWS CDK (Cloud Development Kit) is an infrastructure-as-code framework that allows you to define cloud resources using familiar programming languages. It generates CloudFormation templates, providing a higher-level abstraction for infrastructure deployment.

What programming languages does AWS CDK support?

AWS CDK supports multiple programming languages including TypeScript, JavaScript, Python, Java, C#, and Go. This allows developers to use their preferred language for defining cloud infrastructure.

How does AWS CDK improve infrastructure management?

AWS CDK enhances infrastructure management by enabling code reuse, leveraging object-oriented programming concepts, and providing high-level constructs. It also offers better tooling support and integration with IDEs for improved developer productivity.