Last active
January 15, 2025 11:37
-
-
Save JustinShenk/312b5e0ab7acc3b116f7bf3b6d888fa4 to your computer and use it in GitHub Desktop.
Google Cloud Platform (GCP) instance idle shutdown
This file contains hidden or 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
#!/bin/bash | |
# Add to instance metadata with `gcloud compute instances add-metadata \ | |
# instance-name --metadata-from-file startup-script=idle-shutdown.sh` and reboot | |
# NOTE: requires `bc`, eg, sudo apt-get install bc | |
# Modified from https://stackoverflow.com/questions/30556920/how-can-i-automatically-kill-idle-gce-instances-based-on-cpu-usage | |
threshold=0.1 | |
count=0 | |
wait_minutes=60 | |
while true | |
do | |
load=$(uptime | sed -e 's/.*load average: //g' | awk '{ print $1 }') # 1-minute average load | |
load="${load//,}" # remove trailing comma | |
res=$(echo $load'<'$threshold | bc -l) | |
if (( $res )) | |
then | |
echo "Idling.." | |
((count+=1)) | |
fi | |
echo "Idle minutes count = $count" | |
if (( count>wait_minutes )) | |
then | |
echo Shutting down | |
# wait a little bit more before actually pulling the plug | |
sleep 300 | |
sudo poweroff | |
fi | |
sleep 60 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @OptogeneticsandNeuralEngineeringCore!
If you use a custom script to idle shutdown, Vertex AI Workbench will not terminate Instances normally. To resolve this, you can modify the default Idle Shutdown script to use it. As you know, if you are using an instance of Vertex AI workbench, the Idle Shutdown feature is built-in by default.
However, if you use an editor such as VSCode to execute code via remote ssh connection, the default idle shutdown feature may be activated during code execution, causing the instance to be terminated. To prevent this case, I modified the script as below, referring to @OptogeneticsandNeuralEngineeringCore's script.
The modification is to check the CPU and GPU utilization and if it is below a certain percentage, it is considered as IDLE. If you modify this script and paste it into
/opt/deeplearning/bin/check_idle_shutdown.sh
,check_idle_shutdown.sh
process will refer to the CPU and GPU utilization and shut down the instance when the criteria is met. (Note that you will need sudo privileges to modify the script).