AWS CDK: Infrastructure as TypeScript

AWS Cloud Development Kit (CDK) lets you define AWS infrastructure using TypeScript (or Python, C#, Java). Here’s why it’s worth learning.

Cloud infrastructure
Photo by NASA on Unsplash

Getting Started

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

Simple Stack

import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class MyStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string) {
    super(scope, id);

    // S3 bucket
    const bucket = new s3.Bucket(this, 'MyBucket', {
      versioned: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
    });

    // Lambda function
    const fn = new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('lambda'),
    });

    // Grant read access
    bucket.grantRead(fn);
  }
}

Deploy

cdk synth   # Generate CloudFormation
cdk diff    # Preview changes
cdk deploy  # Deploy to AWS

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.