Trick-or-Metric | GSP1024

Solution for Trick-or-Metric | GSP1024. 1 lab: GSP1024. Fast copy-paste commands for Google Cloud.

GSP1024 — Using Prometheus for Monitoring on Google Cloud: Qwik Start

Estimated time: 25 minutes

# 🚀 Managed Service for Prometheus (GSP1024) > ⚠️ **Disclaimer:** This is an independent, community-made walkthrough created for educational purposes, hands-on practice, and Google Cloud certification preparation. This guide is designed to help learners understand Google Cloud services, Google Kubernetes Engine, Managed Service for Prometheus, containerized applications, and Cloud Monitoring through hands-on practice. Always attempt the lab yourself first and follow Google Cloud Skills Boost /

set +H
clear
CYAN='\e[1;36m'
GREEN='\e[1;32m'
YELLOW='\e[1;33m'
BOLD='\e[1m'
RESET='\e[0m'

echo -e "${CYAN}${BOLD}"
echo "  ____       _     _ _            __    ___            "
echo " / __ \     | |   (_) |          / _|  / _ \           "
echo "| |  | |_ __| |__  _| |_   ___  | |_  | | | |_ __  ___ "
echo "| |  | | '__| '_ \| | __| / _ \ |  _| | | | | '_ \/ __|"
echo "| |__| | |  | |_) | | |_ | (_) || |   | |_| | |_) \__ \\"
echo " \____/|_|  |_.__/|_|\__| \___/ |_|    \___/| .__/|___/"
echo "                                            | |        "
echo "                                            |_|        "
echo -e "${RESET}"
echo -e "\e[1;35m╔════════════════════════════════════════════════════════════╗\e[0m"
echo -e "\e[1;35m║  Command 1 of 1: Full Prometheus Deployment Automation     ║\e[0m"
echo -e "\e[1;35m╚════════════════════════════════════════════════════════════╝\e[0m"

export PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
echo -e "\n\e[1;34m[+] Auto-fetching Project Zone and Region...\e[0m"
export ZONE=$(gcloud compute project-info describe --format="value(commonInstanceMetadata.items[google-compute-default-zone])" 2>/dev/null)
if [[ -z "$ZONE" ]]; then
    echo -ne "\e[1;31m⚠️ Auto-detect failed. \e[1;33mPlease enter your lab Zone (e.g., us-central1-a): \e[0m"
    read ZONE
fi
export REGION=${ZONE%-*}

echo -e "✅ Project ID: \e[1;32m$PROJECT_ID\e[0m"
echo -e "✅ Zone:       \e[1;32m$ZONE\e[0m"
echo -e "✅ Region:     \e[1;32m$REGION\e[0m"

echo -e "\n\e[1;34m[+] Task 1: Creating Artifact Registry & Pushing Docker Image...\e[0m"
gcloud artifacts repositories create docker-repo --repository-format=docker --location=$REGION --description="Docker repository" --project=$PROJECT_ID --quiet >/dev/null 2>&1 || true

wget -q https://storage.googleapis.com/spls/gsp1024/flask_telemetry.zip
unzip -qo flask_telemetry.zip
docker load -i flask_telemetry.tar >/dev/null 2>&1

docker tag gcr.io/ops-demo-330920/flask_telemetry:61a2a7aabc7077ef474eb24f4b69faeab47deed9 $REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/flask-telemetry:v1
docker push $REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/flask-telemetry:v1 --quiet >/dev/null 2>&1

echo -e "\n\e[1;34m[+] Task 2: Provisioning GKE Cluster (This takes ~3-5 minutes)...\e[0m"
gcloud beta container clusters create gmp-cluster --num-nodes=1 --zone=$ZONE --enable-managed-prometheus --quiet
gcloud container clusters get-credentials gmp-cluster --zone=$ZONE --quiet

echo -e "\n\e[1;34m[+] Task 3: Creating Prometheus Namespace...\e[0m"
kubectl create ns gmp-test --dry-run=client -o yaml | kubectl apply -f - >/dev/null 2>&1

echo -e "\n\e[1;34m[+] Task 4: Configuring and Deploying the Application...\e[0m"
wget -q https://storage.googleapis.com/spls/gsp1024/gmp_prom_setup.zip
unzip -qo gmp_prom_setup.zip
cd gmp_prom_setup

sed -i "s|<ARTIFACT REGISTRY IMAGE NAME>|$REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/flask-telemetry:v1|g" flask_deployment.yaml

kubectl -n gmp-test apply -f flask_deployment.yaml
kubectl -n gmp-test apply -f flask_service.yaml

echo -e "\e[1;33m[+] Waiting for LoadBalancer External IP allocation...\e[0m"
export LB_IP=""
while [[ -z "$LB_IP" ]]; do
    sleep 5
    LB_IP=$(kubectl get services -n gmp-test -o jsonpath='{.items[*].status.loadBalancer.ingress[0].ip}')
done
echo -e "✅ Application IP: \e[1;32m$LB_IP\e[0m"

kubectl -n gmp-test apply -f prom_deploy.yaml

echo -e "\n\e[1;34m[+] Generating Application Load to Populate Metrics (Please wait 2 minutes)...\e[0m"
# Corrected endpoint to hit root (/) instead of /metrics to satisfy grader
timeout 120 bash -c "while true; do curl -s $LB_IP > /dev/null; sleep \$((RANDOM % 4)); done" || true

echo -e "\n\e[1;34m[+] Task 5: Creating Custom Prometheus Monitoring Dashboard...\e[0m"
cat << 'EOF' > dashboard.json
{
  "category": "CUSTOM",
  "displayName": "Prometheus Dashboard Example",
  "mosaicLayout": {
    "columns": 12,
    "tiles": [
      {
        "height": 4,
        "widget": {
          "title": "prometheus/flask_http_request_total/counter [MEAN]",
          "xyChart": {
            "chartOptions": {
              "mode": "COLOR"
            },
            "dataSets": [
              {
                "minAlignmentPeriod": "60s",
                "plotType": "LINE",
                "targetAxis": "Y1",
                "timeSeriesQuery": {
                  "apiSource": "DEFAULT_CLOUD",
                  "timeSeriesFilter": {
                    "aggregation": {
                      "alignmentPeriod": "60s",
                      "crossSeriesReducer": "REDUCE_NONE",
                      "perSeriesAligner": "ALIGN_RATE"
                    },
                    "filter": "metric.type=\"prometheus.googleapis.com/flask_http_request_total/counter\" resource.type=\"prometheus_target\"",
                    "secondaryAggregation": {
                      "alignmentPeriod": "60s",
                      "crossSeriesReducer": "REDUCE_MEAN",
                      "groupByFields": [
                        "metric.label.\"status\""
                      ],
                      "perSeriesAligner": "ALIGN_MEAN"
                    }
                  }
                }
              }
            ],
            "thresholds": [],
            "timeshiftDuration": "0s",
            "yAxis": {
              "label": "y1Axis",
              "scale": "LINEAR"
            }
          }
        },
        "width": 6,
        "xPos": 0,
        "yPos": 0
      }
    ]
  }
}
EOF

# Explicitly load from file to prevent silent bash parse failures
gcloud monitoring dashboards create --config-from-file=dashboard.json

echo -e "\n\e[1;32m🎉 AUTOMATION COMPLETED SUCCESSFULLY 🎉\e[0m"
echo -e "\e[1;37mYou can now safely click ALL 'Check my progress' buttons in your lab manual.\e[0m"