0

I am quite new to the GCP platform. I wanted to find out if it were possible to publish to a Google Cloud Pubsub topic from within a Preemptible Compute Engine VM's shutdown script, other than performing REST calls to the PubSub API?

I would like to notify myself each time a Compute Engine Preemptible VM has been scheduled to be preempted.

martinomburajr
  • 1,235
  • 14
  • 29

1 Answers1

1

There is a comprehensive tutorial here. Briefly, it uses the Python Client Library to publish to a specific topic (more here, including other languages). The script and credentials are saved in an image to be able to automate it for future VMs. Then you can just invoke the script with the --metadata flag where the key would be shutdown-script and the value the bash script that calls the code. For example:

gcloud compute instances create <instance-name> --preemptible --image <image-name> \
--zone <zone> --metadata shutdown-script="#! /bin/bash
    sudo su -
    python /path/to/script.py"

Alternatively, instead of saving the image and pointing to the Python script, you could just dump the python code into the bash shutdown script with the -c argument as explained here.

Guillem Xercavins
  • 6,938
  • 1
  • 16
  • 35
  • 3
    Even easier, just set your shutdown script to run [`gcloud pubsub topics publish TOPIC [--message=MESSAGE]`](https://cloud.google.com/sdk/gcloud/reference/pubsub/topics/publish). – Jofre Feb 27 '18 at 20:55
  • Thanks Guillem I see what you are getting at, but @Jofre method is pretty simple! Can't believe I forgot about that! – martinomburajr Feb 28 '18 at 06:45