Course page
Log in

You are watching a free preview. Enroll to open all 25 lessons, track progress and ask the course tutor.

Enroll for $59.99

Section 1: CDK fundamentals

How CDK turns code into CloudFormation

Video 9 min Lesson 1 of 25 Sample clip Preview

CDK is a code generator with opinions. You write TypeScript that creates objects called constructs. When you run cdk synth, CDK executes your program and produces a CloudFormation template. When you run cdk deploy, it hands that template to CloudFormation, which creates, updates or deletes resources.

That flow matters because it tells you where errors come from:

  • TypeScript errors happen when you compile: wrong property names, wrong types.
  • Synthesis errors happen when CDK runs your code: missing context, invalid combinations.
  • Deployment errors come from CloudFormation and AWS: permissions, limits, names already taken.

The building blocks

  • App: the root of the tree, created in bin/.
  • Stack: a unit of deployment that becomes one CloudFormation stack.
  • Construct: anything inside a stack, from a single resource to a whole pattern.
import { App, Stack, StackProps, RemovalPolicy } from "aws-cdk-lib";
import { Bucket, BlockPublicAccess, BucketEncryption } from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";

class StorageStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    new Bucket(this, "Reports", {
      blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
      encryption: BucketEncryption.S3_MANAGED,
      enforceSSL: true,
      versioned: true,
      removalPolicy: RemovalPolicy.RETAIN,
    });
  }
}

const app = new App();
new StorageStack(app, "StorageStack");

Every construct receives a scope (its parent) and an id (unique among its siblings). The path of ids through the tree becomes the logical id in CloudFormation. Change an id, and CloudFormation sees a different resource: it will create a new one and delete the old one. For a bucket or database, that can mean data loss, which is why removalPolicy: RETAIN exists and why we review diffs carefully.

Why choose CDK

Compared with writing CloudFormation YAML by hand, CDK gives you sensible defaults, type checking, reuse through classes and functions, and much less code. Compared with Terraform, it is AWS focused and uses CloudFormation's managed state rather than a state file you must store. Both are good tools; CDK fits teams that live mostly on AWS and like writing TypeScript.

← → switch lessons