Skip to content
Go back

Managing Infrastructure with AWS CDK and TypeScript

Managing Infrastructure with AWS CDK and TypeScript

Introduction

AWS CDK enables defining cloud infrastructure using familiar TypeScript. This guide covers setting up CDK, defining a VPC, Lambda, and RDS instance.

Prerequisites

Step 1: Initialize CDK Project

mkdir cdk-infra
cd cdk-infra
cdk init app --language typescript

Step 2: Install AWS Constructs

npm install aws-cdk-lib constructs

Step 3: Define Infrastructure

Edit lib/cdk-infra-stack.ts:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as rds from 'aws-cdk-lib/aws-rds';

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

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

    // RDS instance
    const db = new rds.DatabaseInstance(this, 'Postgres', {
      engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_14 }),
      vpc,
      credentials: rds.Credentials.fromGeneratedSecret('admin'),
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.MEDIUM),
      multiAz: true,
      allocatedStorage: 100,
    });

    // Lambda function
    const fn = new lambda.Function(this, 'Handler', {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: 'handler.main',
      code: lambda.Code.fromAsset('lambda'),
      vpc,
      environment: {
        DB_SECRET: db.secret?.secretArn || '',
        DB_NAME: db.instanceIdentifier,
      },
    });

    // Grant Lambda access to DB credentials
    db.secret?.grantRead(fn);
  }
}

Step 4: Deploy

cdk bootstrap
cdk deploy

Summary

CDK with TypeScript offers a powerful, reusable, and type-safe way to manage cloud infrastructure as code, integrating VPCs, databases, and compute in a single project.


Share this post on:

Previous Post
Monitoring AWS Lambda Performance with CloudWatch
Next Post
Setting Up AWS RDS with PostgreSQL for Production