Skip to content

Instantly share code, notes, and snippets.

@ohsawa0515
Last active October 28, 2019 10:31
Show Gist options
  • Save ohsawa0515/b048d47aea4c63a4d0b2498a4080a704 to your computer and use it in GitHub Desktop.
Save ohsawa0515/b048d47aea4c63a4d0b2498a4080a704 to your computer and use it in GitHub Desktop.
Safely shutdown a preemptible GCE instance (Powershell)
$instanceName = Invoke-RestMethod -Headers @{ 'Metadata-Flavor' = 'Google' } -Uri "http://metadata.google.internal/computeMetadata/v1/instance/name"
$zoneInfo = Invoke-RestMethod -Headers @{ 'Metadata-Flavor' = 'Google' } -Uri "http://metadata.google.internal/computeMetadata/v1/instance/zone"
$zone = $zoneInfo.Split("/")[-1]
$region = $zone.Substring(0, $zone.Length-2)
$createdBy = gcloud compute instances describe $instanceName --zone $zone --format "value[](metadata.items.created-by)"
$instanceGroup = $createdBy.Split("/")[-1]
$preempted = Invoke-RestMethod -Headers @{ 'Metadata-Flavor' = 'Google' } -Uri "http://metadata.google.internal/computeMetadata/v1/instance/preempted"
try {
if ($preempted -eq "TRUE") {
# Delete instance from regional instance group
gcloud compute instance-groups managed delete-instances $instanceGroup --instances $instanceName --region $region
}
} catch {
# Delete instance from zonal instance group
gcloud compute instance-groups managed delete-instances $instanceGroup --instances $instanceName --zone $zone
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment