← Back to Docs
Recipe

AWS CDK Primer

Infrastructure as code with TypeScript — define your cloud stack, not YAML.

Why CDK

The AWS Cloud Development Kit lets you model infrastructure using familiar programming languages. Constructs compose into stacks, stacks deploy as CloudFormation. No more hand-editing JSON templates at 2 AM.

Bootstrap

npx cdk bootstrap aws://ACCOUNT/REGION

One-time per account/region. Creates the CDK toolkit stack with S3 bucket and IAM roles.

First Stack

import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
export class ApiStack extends cdk.Stack {
  constructor(scope, id, props) {
    super(scope, id, props);
    new lambda.Function(this, 'Handler', {
      runtime: lambda.Runtime.NODEJS_20_X,
      code: lambda.Code.fromAsset('lambda'),
      handler: 'index.handler',
    });
  }
}

Deploy

npx cdk deploy

Synthesizes CloudFormation, uploads assets, and executes the change set. Add --hotswap for rapid dev iteration on Lambda code.

Key Constructs

  • Stack — unit of deployment, maps 1:1 to CloudFormation stack
  • Construct — reusable cloud component (L1 = raw CFN, L2 = curated, L3 = patterns)
  • App — root container for all stacks

Pro tip: Use cdk diff before every deploy. It shows exactly what will change — saves you from accidentally nuking a production database.