Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.