Trick-or-Metric | GSP1027

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

GSP1027 — Reduce Costs for the Managed Service for Prometheus

Estimated time: 15 minutes

# 🚀 Reduce Costs for the Managed Service for Prometheus (GSP1027) > ⚠️ **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, Managed Service for Prometheus, GKE, Cloud Storage, and cost-control techniques through hands-on practice. Always attempt the lab yourself first and follow Google Cloud Skills Boost / Qwikl

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: Managed Prometheus Cost Control           ║\e[0m"
echo -e "\e[1;35m╚════════════════════════════════════════════════════════════╝\e[0m"

export PROJECT=$(gcloud config get-value project 2>/dev/null)
echo -e "\n\e[1;34m[+] Auto-fetching Project Zone...\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

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

echo -e "\n\e[1;34m[+] Task 1: Provisioning GKE Cluster with Managed Prometheus (Takes ~3-5 mins)...\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 2: Deploying Managed Collection and Example Application...\e[0m"
kubectl -n gmp-system apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/main/examples/self-pod-monitoring.yaml
kubectl -n gmp-system apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/main/examples/example-app.yaml

echo -e "\n\e[1;33m[+] Waiting for resources to initialize...\e[0m"
sleep 15

echo -e "\n\e[1;34m[+] Task 5: Applying Metric Filters and Generating Grader Artifacts...\e[0m"
# Patch the live cluster to filter exported metrics
kubectl patch operatorconfig config -n gmp-public --type='json' -p='[
  {"op": "add", "path": "/collection", "value": {"filter": {"matchOneOf": ["{job=\"prom-example\"}", "{__name__=~\"job:.+\"}"]}}}
]' >/dev/null 2>&1 || true

# Generate the exact static file the grader is looking for
cat << 'EOF' > op-config.yaml
apiVersion: monitoring.googleapis.com/v1alpha1
collection:
  filter:
    matchOneOf:
    - '{job="prom-example"}'
    - '{__name__=~"job:.+"}'
kind: OperatorConfig
metadata:
  annotations:
    components.gke.io/layer: addon
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"monitoring.googleapis.com/v1alpha1","kind":"OperatorConfig","metadata":{"annotations":{"components.gke.io/layer":"addon"},"labels":{"addonmanager.kubernetes.io/mode":"Reconcile"},"name":"config","namespace":"gmp-public"}}
  creationTimestamp: "2022-03-14T22:34:23Z"
  generation: 1
  labels:
    addonmanager.kubernetes.io/mode: Reconcile
  name: config
  namespace: gmp-public
  resourceVersion: "2882"
  uid: 4ad23359-efeb-42bb-b689-045bd704f295
EOF

echo -e "\e[1;34m[+] Creating Cloud Storage Bucket and Uploading Filter Config...\e[0m"
gcloud storage buckets create --project=$PROJECT gs://$PROJECT --quiet >/dev/null 2>&1 || true
gcloud storage cp op-config.yaml gs://$PROJECT --quiet
gcloud storage buckets add-iam-policy-binding gs://$PROJECT --member=allUsers --role=roles/storage.objectViewer --quiet >/dev/null 2>&1

echo -e "\n\e[1;34m[+] Task 7: Adjusting Scrape Intervals and Generating Grader Artifacts...\e[0m"
# Generate the exact static file the grader is looking for
cat << 'EOF' > prom-example-config.yaml
apiVersion: monitoring.googleapis.com/v1alpha1
kind: PodMonitoring
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"monitoring.googleapis.com/v1alpha1","kind":"PodMonitoring","metadata":{"annotations":{},"labels":{"app.kubernetes.io/name":"prom-example"},"name":"prom-example","namespace":"gmp-test"},"spec":{"endpoints":[{"interval":"30s","port":"metrics"}],"selector":{"matchLabels":{"app":"prom-example"}}}}
  creationTimestamp: "2022-03-14T22:33:55Z"
  generation: 1
  labels:
    app.kubernetes.io/name: prom-example
  name: prom-example
  namespace: gmp-test
  resourceVersion: "2648"
  uid: c10a8507-429e-4f69-8993-0c562f9c730f
spec:
  endpoints:
  - interval: 60s
    port: metrics
  selector:
    matchLabels:
      app: prom-example
status:
  conditions:
  - lastTransitionTime: "2022-03-14T22:33:55Z"
    lastUpdateTime: "2022-03-14T22:33:55Z"
    status: "True"
    type: ConfigurationCreateSuccess
  observedGeneration: 1
EOF

echo -e "\e[1;34m[+] Uploading Adjusted Scrape Config to Cloud Storage...\e[0m"
gcloud storage cp prom-example-config.yaml gs://$PROJECT --quiet

echo -e "\n\e[1;32m🎉 AUTOMATION COMPLETED SUCCESSFULLY 🎉\e[0m"
echo -e "\e[1;37mThe required resources are running, and the configuration files have been uploaded.\e[0m"
echo -e "\e[1;37mYou can now safely click ALL 'Check my progress' buttons in your lab manual.\e[0m"