Skip to content

Instantly share code, notes, and snippets.

@ohsawa0515
Last active October 28, 2019 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohsawa0515/f664763eb45bd430d294b233ceaa61f8 to your computer and use it in GitHub Desktop.
Save ohsawa0515/f664763eb45bd430d294b233ceaa61f8 to your computer and use it in GitHub Desktop.
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