AWS CDK: Infrastructure in Real Code

Define the whole NoteSnap backend in about 20 lines of TypeScript.

1 min read

The AWS Cloud Development Kit (CDK) lets you define infrastructure in a programming language. You get loops, functions, autocompletion, and type checking, and CDK synthesizes a CloudFormation template for you.

CDK's high-level constructs come with sensible defaults and helper methods. bucket.grantRead(fn) writes the least-privilege IAM policy for you.

Try it

lib/notesnap-stack.ts
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { S3EventSource } from 'aws-cdk-lib/aws-lambda-event-sources';

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

    const uploads = new s3.Bucket(this, 'Uploads', { versioned: true });

    const table = new dynamodb.TableV2(this, 'Summaries', {
      partitionKey: { name: 'noteId', type: dynamodb.AttributeType.STRING },
    });

    const summarize = new lambda.Function(this, 'Summarize', {
      runtime: lambda.Runtime.PYTHON_3_13,
      handler: 'lambda_function.lambda_handler',
      code: lambda.Code.fromAsset('lambda'),
      timeout: Duration.seconds(30),
      environment: { TABLE_NAME: table.tableName },
    });

    uploads.grantRead(summarize);       // least-privilege S3 read
    table.grantWriteData(summarize);    // least-privilege DynamoDB write
    summarize.addEventSource(new S3EventSource(uploads, {
      events: [s3.EventType.OBJECT_CREATED],
      filters: [{ prefix: 'notes/' }],
    }));
  }
}

The CDK workflow

Terminal
npm install -g aws-cdk
cdk init app --language typescript   # new project
cdk bootstrap                        # once per account/Region: creates CDK's helper resources
cdk synth                            # show the generated CloudFormation
cdk diff                             # preview changes against what's deployed
cdk deploy                           # deploy
cdk destroy                          # tear down

Those ~25 lines produce a bucket, a table, a function, an IAM role with scoped policies, and the S3 trigger, which would be well over 100 lines of raw CloudFormation.

Tip

The function still needs Bedrock permission. Add it with summarize.addToRolePolicy(new iam.PolicyStatement({ actions: ['bedrock:InvokeModel'], resources: ['*'] })), then scope resources to your model's ARN.

Key takeaways

  • CDK writes infrastructure in real code and synthesizes CloudFormation.
  • grant* methods generate least-privilege IAM policies automatically.
  • bootstrap once, then synth, diff, and deploy.

Check your understanding

Pick an answer to see the explanation.

  1. 1. What does `cdk diff` do?