AWS CDK: Deploy static files to an Amazon S3 Bucket

February 1st, 2020 141 Words

You can easily deploy static files stored in a folder to an Amazon S3 Bucket. If you configure your S3 Bucket for static website hosting, you can access all files via HTTPS from any browser or tool. Using the AWS Cloud Development Kit in TypeScript, your CloudFormation Stack can look like this. After the deployment is done, the domain name to access the uploaded content will be exposed as a CloudFormation Stack Output.

import * as CDK from "@aws-cdk/core";
import * as S3 from "@aws-cdk/aws-s3";
import * as S3Deployment from "@aws-cdk/aws-s3-deployment";

const path = "./files";

export class WebsiteStack extends CDK.Stack {
  constructor(app: CDK.App, id: string, props?: CDK.StackProps) {
    super(app, id, props);

    const bucket = new S3.Bucket(this, "Files", {
      websiteIndexDocument: "index.html",
      publicReadAccess: true,
    });

    new S3Deployment.BucketDeployment(this, "Deployment", {
      sources: [S3Deployment.Source.asset(path)],
      destinationBucket: bucket,
    });

    new CDK.CfnOutput(this, "BucketDomain", {
      value: bucket.bucketWebsiteDomainName,
    });
  }
}