Auto shutdown idle gce instance

Tags:

There’s a few posts to do this on the net, but it looks like they miss some points, e.g., not resetting counts when a machine has been idle. This code is improved version.

#!/bin/bash
threshold=0.1
count=0
wait_minutes=30
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
    ((count+=1))
  else
    count=0
  fi
  echo "Idle minutes count = $count"
  if (( count>wait_minutes ))
  then
    echo "Shutting down in 10 sec.."
    # wait a little bit more before actually pulling the plug
    sleep 10
    sudo poweroff
  fi
  sleep 60
done

And then you can add it to your VM like this:

gcloud compute instances add-metadata \
  ${VM_NAME} --zone=${ZONE} \
  --metadata-from-file startup-script=${shutdown_script}
gcloud compute instances reset ${VM_NAME} --zone ${ZONE}