Use AWS CDK to deploy a S3 Bucket, static content, and create Route53 entries

Paul Kukiel
Level Up Coding

--

Static sites are commonplace. Often I’ll build something up as a proof of concept, and to share that with my friends, I’ll make a public s3 bucket and send the link, quick and easy. If I need/want this for a longer period of time I typically create a subdomain and point that to the bucket.

In this example we will:

  • Create a bucket in s3 with CDK
  • Setup the bucket to allow hosting
  • Set the default document
  • Deploy a sample html file to the bucket
  • Look up a root hosted zone
  • Create a new DNS record in an existing zone that points to an s3 bucket

Requirements:

  • AWS CDK npm install -g aws-cdk
  • Node.js — Download Link
  • An AWS account
  • Local credentials ( unless using Cloud 9 )
  • Your Account ID ( required for Route 53 changes )
  • A Zone in Route53

Let’s stat the local setup:

We are now ready to code. Let’s begin creating the files and folders.

Our example Program (index.html) is ready to deploy.

Now open “lib/{stack-name}.ts” and let’s begin coding some infrastructure.

This is very straightforward, remember when creating buckets that the bucket name should match the domain name you intend to point at the bucket.

Be aware that although the removalPolicy is set to destroy, when deleting this stack this will fail unless you remove the files in the bucket. If the bucket is empty when the stack is deleted the bucket will also be deleted.

Deploy the static code to the bucket.

I have an existing zone I want to add a subdomain to. The first step is to look this up. You can look this up by hostZoneId or zoneName. For readability here I have used domain name. Docs <- Here

Next we create a new entry in Route53 and point the entry to the “bucketWebsiteDomainName” of the s3 bucket we created. In this example, it’s “example.url2qr.me”.

The complete code should look like so:

We will also have to pass in the accountID and default region. Open “bin/{stackname}.ts” and set the values. I have them set as env variables, you can hardcode them for example purpose as well.

We are ready to deploy:

cdk bootstrap
cdk deploy

Once complete run:

curl example.{your-domain}

and we should see the contents of the index.html file:

On in a browser:

Full repo: https://github.com/kukielp/aws-cdk-s3

--

--