Setup a static website (CDN) with Terraform on GCP

Kevin P.
The Startup
Published in
3 min readMay 8, 2020

Let’s say you need to quickly deploy a static website, or put some files behind a CDN on GCP. But you also want to do it as code, so you can easily replicate the infrastructure somewhere else if needed.

That’s where you’re going to use Terraform to automate the deployment.

Google Cloud and Terraform logo

What do you need?

Before starting you’ll need some pre-existing configurations:

  • An existing GCP account linked to a billing account
  • A service account with a key
  • Terraform (≥0.12) installed and configured on your machine
  • A domain name managed in Cloud DNS
  • The gcloud command configured
  • Some files to publish to the CDN

You can find all the terraform files in my Github project.

Architecture

Project architecture

The following ressources will be created in the project:

  • An external IP address
  • An entry in Cloud DNS to map the IP address to the domain name
  • A GCS bucket
  • A load balancer with CDN
  • A managed certificate for HTTPS (in beta)

Let’s deploy

Prepare Terraform

You need to configure your Terraform to use the GCP and GCP beta provider first (needed for the managed certificate). Don’t forget to change your variables in the terraform.tfvars file.

Configure Terraform GCP providers

Bucket configuration

We need then to create a GCS bucket to host our static files.

Create GCS bucket

Network configuration

We also need to create a new IP address, and add it in our DNS, so we’ll be able to get HTTPS certificates later.

Create an IP address, and add it to the DNS

LoadBalancer and CDN creation

Finally, we can create our LoadBalancer, the CDN, and map them to serve the bucket content.

Create the loadbalancer

And here’s a schema explaining how the traffic is handle from the internet.

Load balancer components

Deployment

Now that everything is ready, it’s time to start the deployment. Just run the Terraform commands, and after a few minutes everything will be deployed.

terraform init
terraform plan
terraform apply
The loadbalancer in GCP

Publish the website

Let’s try to send a simple hello world page to check if everything works.

gsutil cp hello.html gs://coffeetime-website/

Test the website

Now let’s check if everything is working as it should. Let’s open the URL : https://website.gcp.coffeetime.dev/hello.html

If everything works, you should be able to load the site with a valid HTTPS certificate.

Website from Safari
Website from curl

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Kevin P.
Kevin P.

Written by Kevin P.

SRE @ Somewhere_Redacted. | All opinions are mine.