How to Auto Shutdown An Idle VM Instance on GCP to Cut Fat Bills

Phillip Peng
Analytics Vidhya
Published in
2 min readJan 16, 2021

--

configurations to auto shutdown an idle VM instance on GCP to control your GCP bill

(picture from https://unsplash.com/)

Pay-as-you-go cloud computing (PAYG cloud computing) is a popular cloud computing payment method that charges for use. You only pay when you use the service. It sounds very good except for one catch that you may forget to shutdown the instance, which ends up paying for lots of not-in-use hours. This post walks through how to configure auto-shutdown of an idle VM instance on GCP.

Step 1: Upload the idle-shutdown shell script to the VM instance.

Justin Shenk provides the idle-shutdown shell script as a Github gist (https://gist.github.com/justinshenk/312b5e0ab7acc3b116f7bf3b6d888fa4). The script monitors the CPU usage of the VM instance. We need to upload it to the VM instance.

If you are accessing the VM instance through GCP AI notebook, you can load the file through Terminal under Jupyterlab using the following codes:

cd /opt/deeplearning/binsudo wget https://gist.githubusercontent.com/justinshenk/312b5e0ab7acc3b116f7bf3b6d888fa4/raw/59f021c2bf0388ba36e5a589dba52e233ee84964/idle-shutdown.sh

Make sure that you use the sudo command. Otherwise, the file would not be saved in the folder due to permission.

Step 2: Configure the Metadata of the instance

Next, we need to add a metadata ‘startup-script’ through the VM instance edit mode. Scroll to the ‘Custom metadata’ section, click ‘add item’, enter the ‘startup-script’ in the left box and ‘/opt/deeplearning/bin/idle-shutdown.sh’ (the path to the script we saved in step 1) in the right box. Save and Exit the instance edit mode.

(VM Instance editing Metadata)

Step 3: Configure the start-up script

The default settings in the start-up script is to shut-down the VM instance when the instance cpu usage has been 10% or less for one consecutive hour. You can customize the cpu usage threshold (10%) and/or idle time window (one hour).

Step 4: Install package ‘bc.’

Package ‘bc’ is required to check the instance cpu usage. You can install the packages on Linux VM instance as:

sudo apt-get install bc

If it fails for some Linux versions, you may want to update your apt as below:

sudo apt-get --update
sudo apt-get --upgrade
sudo apt-get install --reinstall apt

Reboot your instance and you should be able to enjoy the auto-shutdown feature to cut the fat cloud bills.

--

--