AWS Learning Journey

Infrastructure in TypeScript or Python? The AWS CDK, Explained

Apps, stacks, constructs, environments, synth, diff, deploy, reusable constructs, and CDK Pipelines — and how it all becomes CloudFormation under the hood.

7 min read · 1284 words
AWSAWS CDKInfrastructure As CodeTypeScriptDevOps
Infrastructure in TypeScript or Python? The AWS CDK, Explained cover image

AWS from Zero to Production — Phase 6, Part 3 of 5 · See the full series roadmap


Here’s a Fargate service behind an Application Load Balancer, in a new VPC, with logging, health checks, and IAM roles:

const vpc = new ec2.Vpc(this, 'Vpc', { maxAzs: 2 });

new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'OrdersApi', {
  vpc,
  desiredCount: 2,
  taskImageOptions: {
    image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest'),
  },
});

That’s it. Those few lines generate hundreds of lines of CloudFormation: subnets, route tables, NAT gateways, security groups, roles, a cluster, a task definition, a service, a load balancer, a listener, and a target group.

That’s the AWS Cloud Development Kit (CDK): infrastructure in a real programming language, with sensible defaults built in. It’s powerful — and like every abstraction, it hides things you still need to understand.

What you’ll walk away with


How CDK works

Your code (TypeScript, Python, Java, C#, Go)
      |
      | cdk synth
      v
CloudFormation template(s) + assets (Docker images, Lambda code)
      |
      | cdk deploy
      v
CloudFormation stack(s) in your account

CDK doesn’t replace CloudFormation — it generates it. Everything you learned in Part 1 still applies: stacks, change sets, rollbacks, drift, and DeletionPolicy.


Apps, stacks, and constructs

const app = new cdk.App();

new NetworkStack(app, 'orders-network-dev', { env: devEnv });
new ServiceStack(app, 'orders-service-dev', { env: devEnv });

The three construct levels

The killer feature: grant methods

L2 constructs can wire up IAM permissions for you:

const bucket = new s3.Bucket(this, 'Uploads', {
  encryption: s3.BucketEncryption.S3_MANAGED,
  blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
  enforceSSL: true,
  versioned: true,
  removalPolicy: cdk.RemovalPolicy.RETAIN,
});

const fn = new lambda.Function(this, 'Resize', { /* ... */ });

bucket.grantRead(fn);

grantRead writes a least-privilege policy on the function’s role — scoped to exactly this bucket. No hand-written JSON, no wildcards.


Environments

An environment is an account and Region pair that a stack deploys to:

const devEnv  = { account: '111111111111', region: 'us-east-1' };
const prodEnv = { account: '222222222222', region: 'us-east-1' };

new ServiceStack(app, 'orders-dev',  { env: devEnv,  desiredCount: 1 });
new ServiceStack(app, 'orders-prod', { env: prodEnv, desiredCount: 4 });

Bootstrapping

Before the first deploy, each environment needs bootstrapping:

cdk bootstrap aws://111111111111/us-east-1

This creates a CDKToolkit stack with an S3 bucket and an ECR repository for assets, plus IAM roles that CDK uses to deploy. For cross-account deployments, bootstrap target accounts with --trust to let a pipeline account deploy into them.


The workflow: synth, diff, deploy

cdk synth                      # generate CloudFormation into cdk.out/
cdk diff orders-dev            # compare with what's deployed
cdk deploy orders-dev          # deploy through CloudFormation
cdk destroy orders-dev         # delete the stack

cdk synth

Runs your code and writes templates and assets to cdk.out/. If your code has a bug, it fails here — before touching AWS. Read the generated template at least once; it’s the best way to understand what CDK is doing for you.

cdk diff

Shows resource changes, IAM and security group changes, and — importantly — replacements. Treat it like a Terraform plan.

cdk deploy

Uploads assets — like building and pushing your Docker image to the bootstrap ECR repository — then creates or updates the stack through a change set. By default, it asks for approval when security-related changes appear.

Engineer’s note: cdk watch and hotswap deployments are great for fast feedback in development. They intentionally skip CloudFormation for some changes, so never use them against production.


Reusable constructs

Your own constructs are just classes. Package your team’s standards once, and reuse them everywhere:

export interface SecureBucketProps {
  readonly retainOnDelete?: boolean;
}

export class SecureBucket extends Construct {
  public readonly bucket: s3.Bucket;

  constructor(scope: Construct, id: string, props: SecureBucketProps = {}) {
    super(scope, id);

    this.bucket = new s3.Bucket(this, 'Bucket', {
      encryption: s3.BucketEncryption.KMS_MANAGED,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      enforceSSL: true,
      versioned: true,
      lifecycleRules: [{ noncurrentVersionExpiration: cdk.Duration.days(30) }],
      removalPolicy: props.retainOnDelete === false
        ? cdk.RemovalPolicy.DESTROY
        : cdk.RemovalPolicy.RETAIN,
    });
  }
}

Now every team gets encrypted, private, versioned buckets by writing new SecureBucket(this, 'Reports'). Publish constructs as packages to share them across repositories.

Testing infrastructure

Because it’s code, you can unit test it:

const template = Template.fromStack(stack);

template.hasResourceProperties('AWS::S3::Bucket', {
  VersioningConfiguration: { Status: 'Enabled' },
});

Tools like cdk-nag check your stacks against security rule packs at synth time.

Aspects

Aspects visit every construct in a scope — useful for organization-wide rules, like “add these tags everywhere” or “fail synth if any bucket is unencrypted.”


CDK Pipelines

CDK Pipelines is a construct library for continuous delivery of CDK apps through AWS CodePipeline:

const pipeline = new pipelines.CodePipeline(this, 'Pipeline', {
  synth: new pipelines.ShellStep('Synth', {
    input: pipelines.CodePipelineSource.connection('acme/orders-infra', 'main', {
      connectionArn: 'arn:aws:codeconnections:us-east-1:111122223333:connection/abc',
    }),
    commands: ['npm ci', 'npm test', 'npx cdk synth'],
  }),
});

pipeline.addStage(new OrdersStage(this, 'Dev',  { env: devEnv }));
pipeline.addStage(new OrdersStage(this, 'Prod', { env: prodEnv }), {
  pre: [new pipelines.ManualApprovalStep('PromoteToProd')],
});

Phase 7 covers AWS-native CI/CD and GitHub Actions in depth.


CDK vs. CloudFormation vs. Terraform

Watch out: “It’s just code” can tempt teams into clever abstractions nobody can follow. Keep stacks simple, prefer composition, and make generated templates easy to review.


Common mistakes


Key takeaways


Quick self-check

Test yourself before moving on:

  1. What does cdk synth produce?
  2. Which construct level gives you sensible defaults and grant methods?
  3. You renamed a construct’s ID from Db to Database. What happens on deploy?
  4. What does cdk bootstrap create?

Answers

  1. CloudFormation templates and assets in cdk.out/.
  2. L2.
  3. Its logical ID changes, so CloudFormation replaces the resource. Check cdk diff first.
  4. An assets bucket, an ECR repository, and deployment roles in the CDKToolkit stack.

What’s next

In Part 4, we automate what happens inside and around your resources with AWS Systems Manager: Parameter Store, Session Manager, Run Command, Patch Manager, Automation, State Manager, and more.

CDK, Terraform, or CloudFormation — which does your team use? Tell me why in the comments.


Share this article

LinkedIn post draft