-
-
Save Shreeyak/0dc7a62fcd65a947e5c090933ef4e1f5 to your computer and use it in GitHub Desktop.
Google Cloud Platform (GCP) instance idle shutdown
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
#!/bin/bash | |
#This script will shut down an instance after 30mins of cpu idling below threshold. | |
# | |
# 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.4 | |
count=0 | |
while true | |
do | |
load=$(uptime | sed -e 's/.*load average: //g' | awk '{ print $3 }') | |
res=$(echo $load'<'$threshold | bc -l) | |
if (( $res )) | |
then | |
echo "Idling.." | |
((count+=1)) | |
fi | |
echo "Idle minutes count = $count" | |
if (( count>30 )) | |
then | |
echo Shutting down | |
# wait a little bit more before actually pulling the plug | |
sleep 2 | |
sudo poweroff | |
fi | |
sleep 60 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment