Keeping GCE Preemptable instances powered on

Preemptive instances cost less, a lot less on Google Compute Engine. I've read up to 80%. As a test for our production cluster use I created this script, which uses the GCloud API.

This can be run from an instance with the appropriate permissions within gcloud, outside via a users cron, or using a service account.

Depending on your version of the gcloud api you may have to modify the gcloud commands slightly.

#!/bin/bash
#
# Script to check google cloud platform machines uptime via GCloud API
# and start them if preempted, or user powers off.
#
# define instance name for script to check.
INSTANCENAME="test"  
SECONDSBETWEENCHECKS=120  
while :; do  
     # get machine list from google cloud, parse out instance, look for terminated.
     if gcloud compute instances list | grep $INSTANCENAME | grep "TERMINATED"; 
     then
         echo "---"
         date
         echo "API machine not running"
         echo "Sending gcloud commands to Google"
         # request google boot the machine.
         gcloud compute instances start $INSTANCENAME 
         echo "sleeping..."
         sleep $SECONDSBETWEENCHECKS
     else
         echo "---"
         date
         echo $INSTANCENAME " is running I'm coo..."
         echo "sleeping..."
         sleep $SECONDSBETWEENCHECKS
     fi
 done

I have a writeup on making systemd unit files and enabling a service on boot. linked here