Cloud Monitoring: Qwik Start

Solution for Cloud Monitoring: Qwik Start. 1 lab: GSP089. Fast copy-paste commands for Google Cloud.

GSP089 — Cloud Monitoring: Qwik Start

Estimated time: 20 minutes

# 📊 Cloud Monitoring: Qwik Start > ⚠️ **Disclaimer:** This is an independent, community-made walkthrough created to help you understand why each step works. Attempt the lab yourself first and use this guide as a learning aid rather than as a shortcut to skip the underlying concepts. This guide is intended for educational purposes, hands-on practice, and Google Cloud certification preparation. It is not affiliated with, endorsed by, or officially supported by Google, Google Cloud, Google Cloud

# ==============================================================================
# Color Variables & Branding
# ==============================================================================
GREEN='\e[1;32m'
CYAN='\e[1;36m'
YELLOW='\e[1;33m'
MAGENTA='\e[1;35m'
RED='\e[1;31m'
RESET='\e[0m'
BOLD='\e[1m'

clear
echo -e "${CYAN}${BOLD}"
cat << "EOF"
  ____       _     _ _            __    ___            
 / __ \     | |   (_) |          / _|  / _ \           
| |  | |_ __| |__  _| |_   ___  | |_  | | | |_ __  ___ 
| |  | | '__| '_ \| | __| / _ \ |  _| | | | | '_ \/ __|
| |__| | |  | |_) | | |_ | (_) || |   | |_| | |_) \__ \
 \____/|_|  |_.__/|_|\__| \___/ |_|    \___/| .__/|___/
                                            | |        
                                            |_|        
EOF
echo -e "${RESET}"
echo -e "${MAGENTA}${BOLD}>>> ORBIT OF OPS: GSP089 PART 1 INITIALIZED <<<${RESET}\n"

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Auto-fetching Project and Zone...${RESET}"
export PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
if [[ -z "$PROJECT_ID" ]]; then
    export PROJECT_ID=$DEVSHELL_PROJECT_ID
fi

export ZONE=$(gcloud compute project-info describe \
    --format="value(commonInstanceMetadata.items[google-compute-default-zone])" 2>/dev/null | tail -n 1)

if [[ -z "$ZONE" ]]; then
    read -p "⚠️ Could not auto-detect Zone. Please enter the lab Zone (e.g., us-east1-b): " ZONE
    export ZONE
fi

gcloud config set compute/zone $ZONE 2>/dev/null

echo -e "✅ Project ID: ${GREEN}$PROJECT_ID${RESET}"
echo -e "✅ Zone:       ${GREEN}$ZONE${RESET}\n"

echo -e "${CYAN}${BOLD}⚠️  ATTENTION: USER EMAIL REQUIRED FOR ALERTING ⚠️${RESET}"
read -p "Enter your personal email address: " USER_EMAIL
export USER_EMAIL
echo ""

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Enabling Monitoring APIs & Creating Firewall Rule...${RESET}"
gcloud services enable monitoring.googleapis.com logging.googleapis.com || true

gcloud compute firewall-rules create allow-http \
    --direction=INGRESS --priority=1000 --network=default \
    --action=ALLOW --rules=tcp:80 --source-ranges=0.0.0.0/0 \
    --target-tags=http-server || true

echo -e "${CYAN}${BOLD}[Orbit of Ops] Task 1: Creating 'lamp-1-vm' instance...${RESET}"
gcloud compute instances create lamp-1-vm \
    --zone=$ZONE --machine-type=e2-medium \
    --image-family=debian-11 --image-project=debian-cloud \
    --tags=http-server || true

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Waiting 45 seconds for VM to fully boot...${RESET}"
sleep 45

echo -e "${MAGENTA}${BOLD}[Orbit of Ops] Task 2: Installing Apache and Ops Agent via SSH...${RESET}"
cat << 'EOF' > install.sh
sudo apt-get update
sudo apt-get install -y apache2 php
sudo service apache2 restart
curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
sudo bash add-google-cloud-ops-agent-repo.sh --also-install
EOF

gcloud compute scp install.sh lamp-1-vm:/tmp --zone=$ZONE --quiet
gcloud compute ssh lamp-1-vm --zone=$ZONE --quiet --command="bash /tmp/install.sh"

echo -e "\n${GREEN}${BOLD}✅ Part 1 Complete. Check Tasks 1 & 2 progress in the lab window!${RESET}"
# ==============================================================================
# Color Variables & Branding
# ==============================================================================
GREEN='\e[1;32m'
CYAN='\e[1;36m'
YELLOW='\e[1;33m'
MAGENTA='\e[1;35m'
RESET='\e[0m'
BOLD='\e[1m'

echo -e "\n${MAGENTA}${BOLD}>>> ORBIT OF OPS: GSP089 PART 2 (FINAL VERSION) <<<${RESET}\n"

# Ensure variables are set in case the session reset
export PROJECT_ID=$(gcloud config get-value project 2>/dev/null)
export ZONE=$(gcloud compute instances list --format="value(zone)" | head -n 1)

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Fetching External IP of lamp-1-vm...${RESET}"
export EXTERNAL_IP=$(gcloud compute instances describe lamp-1-vm --zone=$ZONE --format="value(networkInterfaces[0].accessConfigs[0].natIP)")
echo -e "✅ External IP: ${GREEN}$EXTERNAL_IP${RESET}"

echo -e "${CYAN}${BOLD}[Orbit of Ops] Task 3: Creating correct 'URL' type Uptime Check...${RESET}"
curl -s -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" \
  "https://monitoring.googleapis.com/v3/projects/$PROJECT_ID/uptimeCheckConfigs" \
  -d "{
  \"displayName\": \"Lamp Uptime Check\",
  \"monitoredResource\": {
    \"type\": \"uptime_url\",
    \"labels\": { \"project_id\": \"$PROJECT_ID\", \"host\": \"$EXTERNAL_IP\" }
  },
  \"httpCheck\": { \"path\": \"/\", \"port\": 80 },
  \"period\": \"60s\"
}" > /dev/null || true

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Task 4: Creating Notification Channel...${RESET}"
cat > email-channel.json <<EOF
{
  "type": "email",
  "displayName": "orbitofops",
  "description": "Alerting Channel",
  "labels": {
    "email_address": "$USER_EMAIL"
  }
}
EOF
gcloud beta monitoring channels create --channel-content-from-file="email-channel.json" > /dev/null 2>&1 || true

echo -e "${YELLOW}${BOLD}[Orbit of Ops] Fetching Notification Channel ID...${RESET}"
export CHANNEL_ID=$(gcloud beta monitoring channels list --format="value(name)" --filter='displayName="orbitofops"' | head -n 1)
echo -e "✅ Notification Channel ID: ${GREEN}$CHANNEL_ID${RESET}"

echo -e "${CYAN}${BOLD}[Orbit of Ops] Creating Alerting Policy...${RESET}"
cat > alert-policy.json <<EOF
{
  "displayName": "Inbound Traffic Alert",
  "conditions": [
    {
      "displayName": "VM Instance - Network traffic",
      "conditionThreshold": {
        "filter": "resource.type = \"gce_instance\" AND metric.type = \"agent.googleapis.com/interface/traffic\"",
        "aggregations": [
          {
            "alignmentPeriod": "300s",
            "crossSeriesReducer": "REDUCE_NONE",
            "perSeriesAligner": "ALIGN_RATE"
          }
        ],
        "comparison": "COMPARISON_GT",
        "duration": "60s",
        "trigger": {
          "count": 1
        },
        "thresholdValue": 500
      }
    }
  ],
  "combiner": "OR",
  "enabled": true,
  "notificationChannels": [
    "$CHANNEL_ID"
  ]
}
EOF

gcloud alpha monitoring policies create --policy-from-file="alert-policy.json" > /dev/null 2>&1 || true

echo -e "\n${GREEN}${BOLD}🎉 All blocks executed successfully! You have fully completed the lab!${RESET}"