Last active
October 28, 2019 10:31
-
-
Save ohsawa0515/b048d47aea4c63a4d0b2498a4080a704 to your computer and use it in GitHub Desktop.
Safely shutdown a preemptible GCE instance (Powershell)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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