Arcade Simulator: Cloud Infrastructure Engineer | GSP751

Solution for Arcade Simulator: Cloud Infrastructure Engineer | GSP751. 1 lab: GSP751. Fast copy-paste commands for Google Cloud.

GSP751 — Interact with Terraform Modules

Estimated time: 15 minutes

# Interact with Terraform Modules | GSP751 ⚠️ **Disclaimer:** This is an independent, community-made walkthrough created for educational purposes, hands-on practice, and Google Cloud certification preparation. This guide helps learners understand how to use Terraform Registry modules and build reusable local Terraform modules for Google Cloud infrastructure. Always attempt the lab yourself first and follow Google Cloud Skills Boost / Qwiklabs Terms of Service. This walkthrough is not affiliated

CYAN=

\033[0;96m'
GREEN=

\033[0;92m'
YELLOW=

\033[0;93m'
BLUE=

\033[0;94m'
MAGENTA=

\033[0;95m'
WHITE=

\033[0;97m'
BG_BLUE=

\033[44m'
BG_MAGENTA=

\033[45m'
BG_GREEN=

\033[42m'
BOLD=

\033[1m'
RESET=

\033[0m'

clear
echo "${CYAN}${BOLD}"
echo "   ____        _     _ _              __   ___              "
echo "  / __ \      | |   (_) |            / _| / _ \             "
echo " | |  | |_ __ | |__  _| |_   ___    | |_ | | | |_ __  ___   "
echo " | |  | | '__|| '_ \| | __| / _ \   |  _|| | | | '_ \/ __|  "
echo " | |__| | |   | |_) | | |_ | (_) |  | |  | |_| | |_) \__ \  "
echo "  \____/|_|   |_.__/|_|\__| \___/   |_|   \___/| .__/|___/  "
echo "                                               | |          "
echo "                                               |_|          "
echo "${RESET}"

echo "${CYAN}${BOLD}╔════════════════════════════════════════════════════════════════╗${RESET}"
echo "${CYAN}${BOLD}║         🚀 ORBIT OF OPS — GSP751 AUTOMATION: STAGE 1/2         ║${RESET}"
echo "${CYAN}${BOLD}╚════════════════════════════════════════════════════════════════╝${RESET}"
echo ""
echo "${BG_BLUE}${WHITE}${BOLD} ❖ PREREQUISITE & TASK 1: TERRAFORM SETUP & REGISTRY VPC MODULE ${RESET}"
echo ""

echo "${YELLOW}${BOLD}⚡ [STEP 1.1] Configuring ~/.customize_environment & installing Terraform...${RESET}"
cat <<'EOF' > ~/.customize_environment
# Set up HashiCorp repository and install Terraform
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --batch --yes --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install -y terraform
EOF

bash ~/.customize_environment

if [ -f /usr/local/bin/terraform ] && grep -q "developer.hashicorp.com" /usr/local/bin/terraform 2>/dev/null; then
  sudo rm -f /usr/local/bin/terraform
fi
hash -r

echo ""
echo "${CYAN}${BOLD}🔍 [STEP 1.2] Verifying installed Terraform version:${RESET}"
terraform --version
echo ""

echo "${BLUE}${BOLD}🌐 [STEP 1.3] Detecting Project ID, Default Zone, and Region...${RESET}"
export PROJECT_ID=$(gcloud config get-value project)
export ZONE=$(gcloud compute project-info describe --project="$PROJECT_ID" --format="value(commonInstanceMetadata.items[google-compute-default-zone])" 2>/dev/null)
export REGION=$(gcloud compute project-info describe --project="$PROJECT_ID" --format="value(commonInstanceMetadata.items[google-compute-default-region])" 2>/dev/null)

if [ -z "$REGION" ] && [ -n "$ZONE" ]; then
  export REGION="${ZONE%-*}"
fi
if [ -z "$REGION" ]; then
  export REGION=$(gcloud config get-value compute/region 2>/dev/null)
fi
if [ -z "$REGION" ]; then
  read -p "${YELLOW}${BOLD}📍 Enter the lab Region (e.g., us-west1): ${WHITE}" INPUT_REGION
  echo "${RESET}"
  export REGION=$(echo "$INPUT_REGION" | xargs)
fi

sed -i '/export PROJECT_ID=/d' ~/.bashrc
sed -i '/export REGION=/d' ~/.bashrc
echo "export PROJECT_ID=$PROJECT_ID" >> ~/.bashrc
echo "export REGION=$REGION" >> ~/.bashrc

echo "${GREEN}${BOLD}  ✔ Project ID : ${WHITE}${PROJECT_ID}${RESET}"
echo "${GREEN}${BOLD}  ✔ Region     : ${WHITE}${REGION}${RESET}"
echo ""

echo "${MAGENTA}${BOLD}📥 [STEP 1.4] Cloning terraform-google-network (v6.0.1)...${RESET}"
cd ~
rm -rf ~/terraform-google-network
git clone https://github.com/terraform-google-modules/terraform-google-network
cd ~/terraform-google-network
git checkout tags/v6.0.1 -b v6.0.1

echo "${YELLOW}${BOLD}📝 [STEP 1.5] Configuring variables.tf and main.tf in examples/simple_project...${RESET}"
cd ~/terraform-google-network/examples/simple_project

cat <<EOF > variables.tf
variable "project_id" {
  description = "The project ID to host the network in"
  default     = "${PROJECT_ID}"
}

variable "network_name" {
  description = "The name of the network to be created"
  default     = "example-vpc"
}
EOF

cat <<EOF > main.tf
module "test-vpc-module" {
  source       = "terraform-google-modules/network/google"
  version      = "~> 6.0"
  project_id   = var.project_id
  network_name = var.network_name
  mtu          = 1460

  subnets = [
    {
      subnet_name   = "subnet-01"
      subnet_ip     = "10.10.10.0/24"
      subnet_region = "${REGION}"
    },
    {
      subnet_name           = "subnet-02"
      subnet_ip             = "10.10.20.0/24"
      subnet_region         = "${REGION}"
      subnet_private_access = "true"
      subnet_flow_logs      = "true"
    },
    {
      subnet_name               = "subnet-03"
      subnet_ip                 = "10.10.30.0/24"
      subnet_region             = "${REGION}"
      subnet_flow_logs          = "true"
      subnet_flow_logs_interval = "INTERVAL_10_MIN"
      subnet_flow_logs_sampling = 0.7
      subnet_flow_logs_metadata = "INCLUDE_ALL_METADATA"
      subnet_flow_logs_filter   = "false"
    }
  ]
}
EOF

echo "${CYAN}${BOLD}🚀 [STEP 1.6] Initializing and applying Registry Network Module...${RESET}"
terraform init
terraform apply -auto-approve

echo ""
echo "${YELLOW}${BOLD}🧹 [STEP 1.7] Destroying Task 1 VPC infrastructure & cleaning up directory...${RESET}"
terraform destroy -auto-approve
cd ~
rm -rf ~/terraform-google-network

echo ""
echo "${BG_GREEN}${WHITE}${BOLD} ✔ STAGE 1 COMPLETE — CLICK 'CHECK MY PROGRESS' FOR TASK 1      ${RESET}"
echo ""
CYAN=

\033[0;96m'
GREEN=

\033[0;92m'
YELLOW=

\033[0;93m'
BLUE=

\033[0;94m'
MAGENTA=

\033[0;95m'
WHITE=

\033[0;97m'
BG_MAGENTA=

\033[45m'
BG_GREEN=

\033[42m'
BOLD=

\033[1m'
RESET=

\033[0m'

. ~/.bashrc

echo ""
echo "${CYAN}${BOLD}╔════════════════════════════════════════════════════════════════╗${RESET}"
echo "${CYAN}${BOLD}║         🚀 ORBIT OF OPS — GSP751 AUTOMATION: STAGE 2/2         ║${RESET}"
echo "${CYAN}${BOLD}╚════════════════════════════════════════════════════════════════╝${RESET}"
echo ""
echo "${BG_MAGENTA}${WHITE}${BOLD} ❖ TASK 2: BUILD LOCAL GCS STATIC WEBSITE MODULE & UPLOAD FILES ${RESET}"
echo ""

echo "${BLUE}${BOLD}📁 [STEP 2.1] Creating module directory structure in ~/modules/gcs-static-website-bucket...${RESET}"
cd ~
touch main.tf
mkdir -p ~/modules/gcs-static-website-bucket
cd ~/modules/gcs-static-website-bucket
touch website.tf variables.tf outputs.tf

cat <<'EOF' > README.md
# GCS static website bucket

This module provisions Cloud Storage buckets configured for static website hosting.
EOF

cat <<'EOF' > LICENSE
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
EOF

echo "${YELLOW}${BOLD}📝 [STEP 2.2] Writing module configuration files (website.tf, variables.tf, outputs.tf)...${RESET}"
cat <<'EOF' > website.tf
resource "google_storage_bucket" "bucket" {
  name               = var.name
  project            = var.project_id
  location           = var.location
  storage_class      = var.storage_class
  labels             = var.labels
  force_destroy      = var.force_destroy
  uniform_bucket_level_access = true

  versioning {
    enabled = var.versioning
  }

  dynamic "retention_policy" {
    for_each = var.retention_policy == null ? [] : [var.retention_policy]
    content {
      is_locked        = var.retention_policy.is_locked
      retention_period = var.retention_policy.retention_period
    }
  }

  dynamic "encryption" {
    for_each = var.encryption == null ? [] : [var.encryption]
    content {
      default_kms_key_name = var.encryption.default_kms_key_name
    }
  }

  dynamic "lifecycle_rule" {
    for_each = var.lifecycle_rules
    content {
      action {
        type          = lifecycle_rule.value.action.type
        storage_class = lookup(lifecycle_rule.value.action, "storage_class", null)
      }
      condition {
        age                   = lookup(lifecycle_rule.value.condition, "age", null)
        created_before        = lookup(lifecycle_rule.value.condition, "created_before", null)
        with_state            = lookup(lifecycle_rule.value.condition, "with_state", null)
        matches_storage_class = lookup(lifecycle_rule.value.condition, "matches_storage_class", null)
        num_newer_versions    = lookup(lifecycle_rule.value.condition, "num_newer_versions", null)
      }
    }
  }
}
EOF

cat <<'EOF' > variables.tf
variable "name" {
  description = "The name of the bucket."
  type        = string
}

variable "project_id" {
  description = "The ID of the project to create the bucket in."
  type        = string
}

variable "location" {
  description = "The location of the bucket."
  type        = string
}

variable "storage_class" {
  description = "The Storage Class of the new bucket."
  type        = string
  default     = null
}

variable "labels" {
  description = "A set of key/value label pairs to assign to the bucket."
  type        = map(string)
  default     = null
}

variable "bucket_policy_only" {
  description = "Enables Bucket Policy Only access to a bucket."
  type        = bool
  default     = true
}

variable "versioning" {
  description = "While set to true, versioning is fully enabled for this bucket."
  type        = bool
  default     = true
}

variable "force_destroy" {
  description = "When deleting a bucket, this boolean option will delete all contained objects. If false, Terraform will fail to delete buckets which contain objects."
  type        = bool
  default     = true
}

variable "iam_members" {
  description = "The list of IAM members to grant permissions on the bucket."
  type = list(object({
    role   = string
    member = string
  }))
  default = []
}

variable "retention_policy" {
  description = "Configuration of the bucket's data retention policy for how long objects in the bucket should be retained."
  type = object({
    is_locked        = bool
    retention_period = number
  })
  default = null
}

variable "encryption" {
  description = "A Cloud KMS key that will be used to encrypt objects inserted into this bucket"
  type = object({
    default_kms_key_name = string
  })
  default = null
}

variable "lifecycle_rules" {
  description = "The bucket's Lifecycle Rules configuration."
  type = list(object({
    action    = any
    condition = any
  }))
  default = []
}
EOF

cat <<'EOF' > outputs.tf
output "bucket" {
  description = "The created storage bucket"
  value       = google_storage_bucket.bucket
}
EOF

echo "${MAGENTA}${BOLD}🛠️  [STEP 2.3] Writing root module configuration in ~ (main.tf, outputs.tf, variables.tf)...${RESET}"
cd ~

cat <<EOF > main.tf
module "gcs-static-website-bucket" {
  source = "./modules/gcs-static-website-bucket"

  name       = var.name
  project_id = var.project_id
  location   = "${REGION}"

  lifecycle_rules = [{
    action = {
      type = "Delete"
    }
    condition = {
      age        = 365
      with_state = "ANY"
    }
  }]
}
EOF

cat <<'EOF' > outputs.tf
output "bucket-name" {
  description = "Bucket names."
  value       = "module.gcs-static-website-bucket.bucket"
}
EOF

cat <<EOF > variables.tf
variable "project_id" {
  description = "The ID of the project in which to provision resources."
  type        = string
  default     = "${PROJECT_ID}"
}

variable "name" {
  description = "Name of the buckets to create."
  type        = string
  default     = "${PROJECT_ID}"
}
EOF

echo "${CYAN}${BOLD}🚀 [STEP 2.4] Initializing and applying local module in ~...${RESET}"
terraform init
terraform apply -auto-approve

echo ""
echo "${BLUE}${BOLD}🌐 [STEP 2.5] Downloading sample HTML files and uploading to gs://${PROJECT_ID}...${RESET}"
cd ~
curl -sL https://raw.githubusercontent.com/hashicorp/learn-terraform-modules/master/modules/aws-s3-static-website-bucket/www/index.html > index.html
curl -sL https://raw.githubusercontent.com/hashicorp/learn-terraform-modules/blob/master/modules/aws-s3-static-website-bucket/www/error.html > error.html

gcloud storage cp *.html "gs://${PROJECT_ID}"
echo "${GREEN}${BOLD}  ✔ Uploaded index.html and error.html to gs://${PROJECT_ID}.${RESET}"

echo ""
echo "${GREEN}${BOLD}╔════════════════════════════════════════════════════════════════╗${RESET}"
echo "${GREEN}${BOLD}║      🏆 ALL GSP751 LAB TASKS COMPLETED 100% SUCCESSFULLY       ║${RESET}"
echo "${GREEN}${BOLD}╚════════════════════════════════════════════════════════════════╝${RESET}"
echo "${YELLOW}${BOLD}⚠ Click 'Check my progress' for Task 2 before running 'terraform destroy' if desired.${RESET}"
echo ""