← Back
aws cdk

Simple bucket with cdn using cdk

First create the project:

mkdir <name-of-the-stack>
cd <name-of-the-stack>
cdk init app --language=typescript

Add dependencies:

npm i --save @aws-cdk/aws-s3 @aws-cdk/aws-cloudfront

And create the stack:

import * as cdk from "@aws-cdk/core";
import { Bucket } from "@aws-cdk/aws-s3";
import {
CloudFrontWebDistribution,
CloudFrontWebDistributionProps,
OriginAccessIdentity,
} from "@aws-cdk/aws-cloudfront";

const WEBSITE_NAME = "my-site.com";

export class MyStack extends cdk.Stack {
devBucket: Bucket;
cloudfrontDist: CloudFrontWebDistribution;

constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

this.devBucket = new Bucket(this, "unrec-development", {
publicReadAccess: true,
removalPolicy: cdk.RemovalPolicy.DESTROY,
});

// https://dev.to/ryands17/deploying-a-spa-using-aws-cdk-typescript-4ibf
const cloudFrontOAI = new OriginAccessIdentity(this, "OAI", {
comment: `OAI for ${WEBSITE_NAME} website.`,
});

const cloudFrontDistProps: CloudFrontWebDistributionProps = {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: this.devBucket,
originAccessIdentity: cloudFrontOAI,
},
behaviors: [{ isDefaultBehavior: true }],
},
],
};

this.cloudfrontDist = new CloudFrontWebDistribution(
this,
`${WEBSITE_NAME}-cfd`,
cloudFrontDistProps
);
}
}

🖖