iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

AWS CDK

CDK lets you write infrastructure as code in real programming languages - TypeScript here - and synthesises to CloudFormation under the hood.

AWS CDK - first stack

EXAMPLE
// npm install -g aws-cdk
// cdk init app --language typescript

// bin/app.ts
#!/usr/bin/env node
import { App } from 'aws-cdk-lib';
import { ApiStack } from '../lib/api-stack';

const app = new App();
new ApiStack(app, 'ApiStack', {
  env: { region: 'ap-southeast-2', account: '111111111111' },
});


// lib/api-stack.ts
import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { Function, Runtime, Code } from 'aws-cdk-lib/aws-lambda';
import { LambdaRestApi } from 'aws-cdk-lib/aws-apigateway';
import { Table, AttributeType, BillingMode } from 'aws-cdk-lib/aws-dynamodb';

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

    const table = new Table(this, 'Users', {
      partitionKey: { name: 'pk', type: AttributeType.STRING },
      billingMode: BillingMode.PAY_PER_REQUEST,
      pointInTimeRecovery: true,
    });

    const fn = new Function(this, 'ApiFn', {
      runtime: Runtime.NODEJS_20_X,
      handler: 'index.handler',
      code: Code.fromAsset('lambda'),
      timeout: Duration.seconds(10),
      memorySize: 256,
      environment: { TABLE_NAME: table.tableName },
    });

    table.grantReadWriteData(fn);

    new LambdaRestApi(this, 'Api', { handler: fn });
  }
}


// Deploy
// cdk bootstrap                    # one-time per account/region
// cdk synth                        # see the CFN template
// cdk diff                         # what will change
// cdk deploy
// cdk destroy                      # tear down

// Production tips
// - Use App.context for environments: prod, staging, dev
// - Add aspects for tagging and security checks
// - cdk-nag is the de facto linter for CDK
// - Store outputs in SSM so other stacks can reference

Why it matters

CDK gives you loops, conditionals, typed constructs, and an L2 library that bakes in best practices. The trade-off vs raw CloudFormation or Terraform is one of taste; either way, never click around in the console for production infra.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import { Stack } from 'aws-cdk-lib';
import { Bucket } from 'aws-cdk-lib/aws-s3';
class MyStack extends Stack {
    constructor(scope, id) { super(scope, id); new Bucket(this, 'MyBucket'); }
}
Try it Yourself »

Discussion

Loading…