GCP新手求助:能否在Preemptible Compute Engine VM关机脚本中免REST调用发布至Pub/Sub?
Great question! As someone who’s fumbled through GCP’s preemptible VMs as a beginner, I know avoiding raw REST APIs makes things way simpler. You absolutely can send Pub/Sub notifications directly from your shutdown script using the gcloud CLI—no HTTP calls required. Here’s a straightforward, beginner-friendly breakdown:
Prerequisites
- Your preemptible VM needs the Cloud SDK (
gcloud) installed (all official GCP VM images come with this preloaded; if you’re using a custom image, just install it via the package manager or official docs). - The VM’s service account must have the Pub/Sub Publisher role (
roles/pubsub.publisher) assigned to your target Pub/Sub topic. You can set this up via the GCP Console or run this command:gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \ --member="serviceAccount:YOUR_VM_SERVICE_ACCOUNT@YOUR_PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/pubsub.publisher" \ --condition="resource.name == 'projects/YOUR_PROJECT_ID/topics/YOUR_TOPIC_NAME'"
Step 1: Write the Shutdown Script
Create a simple bash script on your VM (e.g., preempt-alert.sh) that uses gcloud to publish your notification:
#!/bin/bash # Send preemption alert to Pub/Sub VM_NAME=$(hostname) SHUTDOWN_TIME=$(date +"%Y-%m-%d %H:%M:%S") MESSAGE="Preemptible VM '$VM_NAME' is being shut down due to preemption at $SHUTDOWN_TIME" # Publish the message to your topic gcloud pubsub topics publish YOUR_TOPIC_NAME --message="$MESSAGE"
Make it executable with:
chmod +x preempt-alert.sh
Step 2: Attach the Script to VM Shutdown
Choose one of these easy methods to ensure the script runs automatically when the VM is preempted:
- Option 1: VM Metadata (Recommended)
Edit your VM’s metadata to add ashutdown-scriptkey with the full content of your script, or useshutdown-script-urlto point to a script stored in a Cloud Storage bucket. This is the most GCP-native way and works seamlessly for preemption events. - Option 2: Local System Setup
For Linux VMs, you can add the script path to/etc/rc.local(before theexit 0line) or create a systemd service that triggers on shutdown. The metadata method is easier to manage at scale, though.
Step 3: Test It Out
Don’t wait for a preemption to verify things work—manually trigger the shutdown script with:
sudo google_metadata_script_runner --script-type shutdown
Check your Pub/Sub topic’s message queue, and you should see your test alert pop up right away.
Quick Tips
- Preemptible VMs only get a 30-second warning before shutdown, so keep your script lightweight. The
gcloudpublish command is fast enough to fit within this window. - If you hit permission errors, double-check the service account role—make sure it’s scoped specifically to your target topic, not just the entire project.
内容的提问来源于stack exchange,提问作者martinomburajr

