Overview
This page explains how to build a static page sit with Google Cloud Storage. The system includes resources in the following and the structure diagram is below.
- Cloud Storage: is used to store the static site contents files
- Cloud DNS: is to offer the DNS record for the Search Console
Prereqiosites
- Prepare the Domain to publish static pages
How to buld the Static Page Site
- Enable API
- Prepare a bucket of the Google Cloud Storage
- Set up Cloud DNS
Attention
Each variable block are in same resource define tf file as the example. But when use these codes, you can separete resources and variables block both to variables.tf andreource name
.tf
Enable API
To manage and create GCP resources, enable apis that is necessary.
gcp_apis.tf
1// Variable for GCP
2variable "gcp_project" {
3 type = object({
4 project = string // The gcp project name
5 region = string // The region of gcp project
6 })
7}
8
9variable "gcp_services" {
10 type = list(string) // Enabling the service name of api
11}
12
13// Enable APIs
14resource "google_project_service" "api_enable" {
15 for_each = toset(var.gcp_services)
16 project = var.gcp_project.project
17 service = each.value
18}
terraform.tfvars
1gcp_services = [
2 "dns.googleapis.com"
3]
Prepare a bucket of the Google Cloud Storage
This part explains how to create a bucket. To expose a bucket, a bucket name need to set same domain name that is registerred in the domain registerer and that bucket iam is set the objectViewer and allUsers.
gcs.tf
1variable "bucket" {
2 type = object({
3 name = string
4 location = string
5 website = optional(object({
6 main = string
7 not_found = string
8 }),
9 { main = "index.html", not_found = "404.html" })
10 clz = optional(string, "STANDARD")
11 })
12}
13
14resource "google_storage_bucket" "content" {
15 name = var.bucket.name
16 location = var.bucket.location
17 uniform_bucket_level_access = true
18
19 // optional
20 storage_class = var.bucket.clz
21 website {
22 main_page_suffix = var.bucket.website.main
23 not_found_page = var.bucket.website.not_found
24 }
25
26 // delete bucket and contents on destroy.
27 force_destroy = true
28}
29
30resource "google_storage_bucket_iam_member" "iam" {
31 depends_on = [google_storage_bucket.content]
32 bucket = google_storage_bucket.content.name
33 role = "roles/storage.objectViewer"
34 member = "allUsers"
35}
Set up Cloud DNS
1variable "dns" {
2 type = object({
3 managed_zone = string
4 ttl = number
5 })
6}
7
8resource "google_dns_record_set" "cname" {
9 name = "${var.bucket.name}."
10 type = "CNAME"
11 ttl = var.dns.ttl
12 managed_zone = var.dns.managed_zone
13 rrdatas = ["c.storage.googleapis.com."]
14}