Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Forked from JustinShenk/idle-shutdown.sh
Last active May 6, 2021 06:03
Show Gist options
  • Save voltrevo/9761791c4c743f8d9b3c8a0938468152 to your computer and use it in GitHub Desktop.
Save voltrevo/9761791c4c743f8d9b3c8a0938468152 to your computer and use it in GitHub Desktop.
Google Cloud Platform (GCP) instance idle shutdown
#!/bin/bash
echo $(date) Start
# 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 $(date) "Idling, incrementing count..."
((count+=1))
else
echo $(date) "Not idling, resetting count..."
((count=0))
fi
echo $(date) "Idle minutes count = $count"
if (( count>wait_minutes ))
then
echo $(date) 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