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.