Understanding AWS CDK Constructs and How to Use Them with CTO.ai

AWS Cloud Development Kit (AWS CDK) is an essential tool to define cloud infrastructure in code and provision it through AWS CloudFormation. Central to the AWS CDK are Constructs, the basic building blocks of AWS CDK apps. Let's dive into the world of AWS CDK Constructs and explore how they can be used in building and deploying applications.

Prerequisites

What is AWS CDK?

The AWS Cloud Development Kit (AWS CDK) is an open-source software development framework by Amazon Web Services (AWS). It allows developers to model and provision their cloud application resources using familiar programming languages. With AWS CDK, you essentially get to leverage the advantages of a software development approach while defining your cloud resources.

Unraveling AWS CDK Constructs

Constructs, the basic building units of AWS CDK apps, represent a cloud component. They encapsulate everything AWS CloudFormation needs to create the component. Constructs can be as simple as an S3 bucket or as complex as a multi-stack application.

Constructs in AWS CDK come in three levels:

  1. Low-Level (L1) Constructs: These map directly to AWS CloudFormation Resources, providing granular control over AWS resources.

  2. High-Level (L3) Constructs: These are pre-packed with sensible defaults and offer a higher level of abstraction to create complex setups with little code.
  3. Middle-Level (L2) Constructs: These are custom abstractions that represent a single AWS resource or a group of resources.

Using AWS CDK Constructs for Building and Deploying Applications

Let’s explore how to use AWS CDK Constructs for building and deploying a simple web application.

Assuming you have AWS CDK installed and configured, let's create a CDK app:

cdk init app --language=typescript

We'll use an L2 construct for Amazon S3 to create an S3 bucket:

import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';

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

    new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
    });
  }
}

Here we're creating an Amazon S3 bucket that will be versioned, and any objects in it will be deleted when the bucket is removed.

To deploy the S3 bucket, we use the cdk deploy command:

cdk deploy

You can use the CDK constructs in our AWS EKS EC2 ASK CDK workflow stack.

import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam'
import * as ec2 from 'aws-cdk-lib/aws-ec2'
import * as eks from 'aws-cdk-lib/aws-eks'
import * as rds from 'aws-cdk-lib/aws-rds'
import * as sqs from 'aws-cdk-lib/aws-sqs'
import * as elasticache from './redis'
import * as autoscaling from 'aws-cdk-lib/aws-autoscaling'
import { Construct } from 'constructs';

interface StackProps {
  org: string
  env: string
  repo: string
  tag: string
  key: string
  entropy: string
}

export default class Cluster extends cdk.Stack {

  public readonly id: string
  public readonly org: string
  public readonly env: string
  public readonly repo: string
  public readonly tag: string
  public readonly key: string
  public readonly entropy: string

  public readonly vpc: ec2.Vpc
  public readonly cluster: eks.Cluster
  public readonly db: rds.ServerlessCluster
  public readonly mq: sqs.Queue
  public readonly redis: Construct
  public readonly bastion: ec2.BastionHostLinux

  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id)
    this.id = id
    this.org = props?.org ?? 'cto-ai'
    this.env = props?.env ?? 'dev'
    this.key = props?.key ?? 'aws-eks-ec2-asg'
    this.repo = props?.repo ?? 'sample-expressjs-aws-eks-ec2-asg-cdk'
    this.tag = props?.tag ?? 'main'
    this.entropy = props?.entropy ?? '01012022'

The code above defines a custom Stack in AWS CDK, which represents a unit of deployment (a collection of AWS resources that are created and managed as a single unit).

Let's break down the different parts:

Imports

The script imports several modules from the aws-cdk-lib package, as well as a redis module from a local file. Each of these modules corresponds to a different type of AWS service.

  • cdk: Core library of AWS CDK.
  • iam: For AWS Identity and Access Management (IAM) resources.
  • ec2: For Amazon Elastic Compute Cloud (EC2) resources.
  • eks: For Amazon Elastic Kubernetes Service (EKS) resources.
  • rds: For Amazon Relational Database Service (RDS) resources.
  • sqs: For Amazon Simple Queue Service (SQS) resources.
  • elasticache: A local module likely used for Amazon ElastiCache resources.
  • autoscaling: For AWS Auto Scaling resources.
  • Construct: Basic building block in AWS CDK.

Interface StackProps

This is a TypeScript interface defining the shape of the properties (props) that can be passed to the Cluster class.

Cluster class and its properties

This is a class Cluster that extends cdk.Stack. It declares several properties which are either the default values or values passed in the props parameter of the constructor. These properties include identifiers, details for the repository, and a unique string entropy.

AWS Resources

The class also declares properties for various AWS resources:

  • vpc: Amazon Virtual Private Cloud (VPC) resource.
  • cluster: Amazon EKS Cluster resource.
  • db: Amazon RDS Serverless Cluster resource.
  • mq: Amazon SQS Queue resource.
  • redis: Likely an Amazon ElastiCache resource from the local redis module.
  • bastion: Amazon EC2 Bastion Host Linux resource, a server that provides access to private network resources from an external network.

Constructor

The constructor function is used to create and initialize an object created from the Cluster class. If certain properties are not provided when creating the object, they are assigned default values (e.g., cto-ai for org, dev for env, and so on).

The super(scope, id) call is necessary as this class extends cdk.Stack, and that parent class needs to be properly constructed with its required parameters (scope and id).

Overall, this script provides a starting point for creating a complex AWS deployment using AWS CDK, and the Cluster class can be extended with methods to create, configure, and connect the various resources.


Enhance Your Cloud Infrastructure Management with CTO.ai

Ready to harness the full potential of AWS CDK for your cloud solutions? Start deploying, managing, and enhancing your AWS resources with CTO.ai today! Sign up for a free trial and take the first step towards a more enhanced and powerful cloud infrastructure management experience.