Skip to content

Instantly share code, notes, and snippets.

@ozaki-r
Last active June 3, 2021 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozaki-r/b9df931e33e119df3a2626e418873bd9 to your computer and use it in GitHub Desktop.
Save ozaki-r/b9df931e33e119df3a2626e418873bd9 to your computer and use it in GitHub Desktop.
GCE: automatically suspend the underlying VM on idle
#!/bin/sh
if [ $# -lt 2 ]; then
echo "usage: $0 name zone [time]"
exit 1
fi
# TODO: check if authenticated and suggest 'gcloud auth login'
name=$1
zone=$2
time=${3:-30}
do_suspend="gcloud beta compute instances suspend $name --quiet --zone $zone"
cnt=0
while true; do
date
# 0.00 0.01 0.11 1/187 628333
cat /proc/loadavg
grep -q '0.00 0.00 0.00' /proc/loadavg
if [ $? = 0 ]; then
cnt=$((cnt + 1))
else
cnt=0
fi
if [ $cnt -ge $time ]; then
$do_suspend &
sleep 20
pkill -x gcloud
fi
sleep 60
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment