Setup a static website (CDN) with Terraform on GCP
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.
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
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.
Bucket configuration
We need then to create a GCS bucket to host our static files.
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.
LoadBalancer and CDN creation
Finally, we can create our LoadBalancer, the CDN, and map them to serve the bucket content.
And here’s a schema explaining how the traffic is handle from the internet.
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
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.