Home
Published on

Deconstructing CDK Application in TypeScript for the Beginners

Author
    Roman Naumenko
    Name
    Roman Naumenko

In our previous blog post, we discussed how to use ChatGPT to generate a basic CDK application. However, as many developers know, building a functioning CDK app takes more than just generating code snippets. It requires understanding of the language-specific configurations.

⁠Many guides and examples for building Cloud Development Kit (CDK) applications start at a high level of complexity, which can be overwhelming. Follow instructions and it works, however it's more like magic. Our approach is to provide a clear understanding of the essential elements required to create a functional CDK app.

We cleaned and simplified generated code and published it at cdk-typescript-barebones repository. It provides a clear, easy-to-follow structure for building a CDK app from scratch. It covers the essential building blocks, how to set up a new CDK app, configure TypeScript, install required npm modules. It is pretty amazing how simple yet powerful and useful CDK app can be!

bin/app.ts is the main entry point of the CDK app. It contains the code that defines the AWS infrastructure resources (we used VPC with 3 subnet types as an example).

This code block is the entry point for an AWS CDK (Cloud Development Kit) application written in TypeScript. It imports necessary modules, initializes the CDK application, and creates a new stack instance using a custom class.

app.ts
#!/usr/bin/env node
import 'source-map-support/register';
import { App } from 'aws-cdk-lib';
import { CfnOutput, Stack, StackProps } from "aws-cdk-lib";
import { Vpc, SubnetType } from "aws-cdk-lib/aws-ec2";
import { Construct } from "constructs";

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

    // Create VPC
    const vpc = new Vpc(this, "VPC", {
      maxAzs: 2,
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: "Public",
          subnetType: SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: "Private",
          subnetType: SubnetType.PRIVATE_WITH_EGRESS,
        },
        {
            cidrMask: 24,
            name: "Isolate",
            subnetType: SubnetType.PRIVATE_ISOLATED,
          },
      ],
      natGateways: 1,
    });

    // Output VPC ID
    new CfnOutput(this, "VpcId", {
      value: vpc.vpcId,
      description: "The VPC ID",
    });

    // Output Subnet IDs
    vpc.privateSubnets.forEach((subnet, index) => {
      new CfnOutput(this, `SubnetId${index}`, {
        value: subnet.subnetId,
        description: `The ID of subnet ${index}`,
      });
    });
  }
}

const app = new App();
new VpcPrivateSubnetStack(app, 'VpcPrivateSubnetStack');

cdk.json is a configuration file that tells CDK CLI how to run application. It specifies the CDK app entry point, which is language specific. It can also specify command-line options to pass to the CDK CLI, such as the AWS profile or region to use.

This code block is a JSON object configuring an AWS CDK application. It sets the command to run the app using "npx ts-node" prioritizing TypeScript files, with "bin/app.ts" as the entry point. The "context" object has a setting to prevent failure during 'cdk diff' if differences are detected.

cdk.json
{
{
  "app": "npx ts-node --prefer-ts-exts bin/app.ts",
  "context": {
    "aws-cdk:enableDiffNoFail": "true"
  }
}

tsconfig.json contains the TypeScript compiler options for the project. It tells the tsc compiler how to compile the TypeScript code into JavaScript and what configuration settings to use.

This code block is a TypeScript configuration file (tsconfig.json) that sets compiler options for output format, strictness, code quality checks, and experimental features. It specifies the files to be compiled using an "include" array with file patterns.

tsconfig.json
{
    "compilerOptions": {
      "target": "ES2018",
      "module": "commonjs",w
      "lib": ["es2018"],
      "declaration": true,
      "strict": true,
      "noImplicitAny": true,
      "strictNullChecks": true,
      "noImplicitThis": true,
      "alwaysStrict": true,
      "noUnusedLocals": true,
      "noUnusedParameters": true,
      "noImplicitReturns": true,
      "noFallthroughCasesInSwitch": true,
      "inlineSourceMap": true,
      "inlineSources": true,
      "experimentalDecorators": true,
      "strictPropertyInitialization": false
    },
    "include": ["bin/*.ts"]
}

package.json contains the metadata and dependencies for the project. It tells the Node Package Manager (NPM) what packages and modules are needed to run the application.

This code block is a package.json file for a minimal AWS CDK TypeScript project. It defines the project's metadata, scripts, and dependencies, such as the AWS CDK and TypeScript packages. The "scripts" section includes commands for testing, building, watching file changes, and working with CDK.

package.json
{
  "name": "min-cdk-typescript",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "lib": "lib"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "tsc",
    "watch": "tsc -w",
    "cdk": "cdk"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-cdk": "^2.74.0",
    "aws-cdk-lib": "^2.0.0",
    "constructs": "^10.0.0",
    "typescript": "^4.1.5"
  }
}

ChatGPT can be an excellent tool for generating CDK code snippets. By starting from scratch and building upon the basics, you can gain a solid foundation for developing robust and scalable cloud infrastructure. Despite its barebones structure, this simple app generates functional Cloudformation template 450 lines long!

Previous Post

← Back to the blog

Services

Overview
AWS CDK CourseNew

Catenary Cloud

© 2021 Catenary Cloud LLC. Made with ❤️ in Philadelphia