Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Safely shutdown a preemptible GCE instance (Bash)
#!/bin/bash
set -u
export PATH="/usr/local/bin:/sbin:/usr/sbin:$PATH"
instance_name=$(curl -sSfL -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/name)
zone_info=$(curl -sSfL -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/zone)
zone=${zone_info##*/}
region=${zone:0:-2}
created_by=$(gcloud compute instances describe ${instance_name} --zone ${zone} --format "value[](metadata.items.created-by)")
instance_group=${created_by##*/}
preempted=$(curl -sSfL http://metadata.google.internal/computeMetadata/v1/instance/preempted -H "Metadata-Flavor: Google")
if [ "${preempted}" = "TRUE" ]; then
# Delete instance from regional instance group
gcloud compute instance-groups managed delete-instances ${instance_group} --instances ${instance_name} --region ${region}
# Delete instance from zonal instance group
if [ $? -ne 0 ]; then
gcloud compute instance-groups managed delete-instances ${instance_group} --instances ${instance_name} --zone ${zone}
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.