Starting and Stopping a VM Using Cloud Function(node.js & python)
Using Google Cloud Function you can easily save you cost of production by schedule switch on/off a Google Compute Engine.

Introduction
In this course of sheet, we will be telling how to start and stop a Google Compute Engine(GCE) VM instance automatically using a scheduling cron job and cloud function.
Setting Up a Node.js Development Environment
This tutorial shows how to prepare your local machine for Node.js development, including developing Node.js applications that run on the Google Cloud Platform. Follow this tutorial to install Node.js and relevant tools.
Before starting Activate Google Cloud Shell
Install Node Version Manager (NVM)
To install or update nvm, you can use the install script
cURL:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
or Wget:
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
To verify that nvm has been installed, do:
command -v nvm
Install Node.js and npm (Node Package Manager)
Once NVM is installed you can install Node.js and npm. To install the latest stable version of Node.js you would run:
>> nvm install stable
To make it the default version run the following:
>> nvm alias default stable
You can check what version of Node.js you're running with:
>> node -v
npm is the Node Package Manager for Node.js and should have been installed alongside Node.js. You use npm to install Node.js packages from the npm repository, for example:
>> npm install --save express
Install Google Cloud SDK
The Google Cloud SDK is a set of tools for the Google Cloud Platform. It contains gcloud, gsutil, and bq, which you can use to access Google Compute Engine, Google Cloud Storage, Google BigQuery, and other products and services from the command line. You can run these tools interactively or in your automated scripts.
Download link: https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe
Install the Google Cloud Client Library for Node.js
npm install --save @google-cloud/compute
Create Google Cloud Function
- Go to Cloud Functions Overview page in the GCP Console
- Make sure that the project for which you enabled Cloud Functions is selected
- Click Create function
- Name your function
- In the Trigger field, select HTTP Trigger.
- In the Source code field, select Inline editor.
- Use the Runtime dropdown to select a runtime.
Create a function startVM
CODE for startVM: index.js
var Compute = require('@google-cloud/compute');
var compute = Compute();
exports.startInstance = function startInstance(req, res) {
var zone = compute.zone('asia-south1-c');
var vm = zone.vm('duo');
vm.start(function(err, operation, apiResponse) {
console.log('instance start successfully');
});
res.status(200).send('DUO has Started!!');
};
CODE for startVM: package.json
{
"name": "sample-http",
"dependencies": {
"@google-cloud/compute": "0.7.1"
},
"version": "0.0.1"
}
Create a function stopVM
CODE for stopVM: index.js
var Compute = require('@google-cloud/compute');
var compute = Compute();
exports.stopInstance = function stopInstance(req, res) {
var zone = compute.zone('asia-south1-c');
var vm = zone.vm('duo');
vm.stop(function(err, operation, apiResponse) {
console.log('instance stop successfully');
});
res.status(200).send('VM has been Stopped!Congrats');
};
CODE for stopVM: package.json
{
"name": "sample-http",
"dependencies": {
"@google-cloud/compute": "0.7.1"
},
"version": "0.0.1"
}
List of Google Cloud Function
In the above image find that both the function has been created successfully.
Test the functions by clicking the Test function option shown below
After doing this we can manually fire each function one at a time to start and stop a VM instance in Google Compute Engine but to do this on scheduling basis we have to write cron jobs which will fire the functions as instructed. Here I have used python to create cron jobs for the call cloud functions. The problem is that NodeJS is only available on App Engine Flexible, but it doesn’t make sense to set up flexible instance just for kicking GCF with cron. Instead, we can create a simple python app and deploy it on App Engine Standard Platform.
Create a Python Application
Before we proceed further install python in your local machine.
Download Link: https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe
Open your favorite editor to write an application. Here I have used a simple notepad.
Prerequisites for the structure:
- A python file for the function startVM ( startVM.py)
- A python file for the function stopVM ( stopVM.py)
- An app.yaml file to set the application URLs
- A cron.yaml file to call the cloud functions as per as the business logic
Create a folder on your local computer and make the following files:
Codes for startVM.py
import webapp2
import urllib2
import mimetypes
class MonthCronPage(webapp2.RequestHandler):
def get(self):
response = urllib2.urlopen('https://asia-northeast1-gcp-test-178407.cloudfunctions.net/startVM')
app = webapp2.WSGIApplication([
('/start', MonthCronPage),
], debug=True)
Codes for stopVM.py
import webapp2
import urllib2
import mimetypes
class MonthCronPage(webapp2.RequestHandler):
def get(self):
response = urllib2.urlopen('https://asia-northeast1-gcp-test-178407.cloudfunctions.net/stopVM')
app = webapp2.WSGIApplication([
('/stop', MonthCronPage),
], debug=True)
Codes for app.yaml
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: startVM.app
- url: /.*
script: stopVM.app
skip_files:
- ^node_modules/.*
Codes for cron.yaml
cron:
- description: "starts job"
url: /start
schedule: 28 of month 00:00
- description: "stops job"
url: /stop
schedule: 2 of month 00:00
Deploy the python application on app engine standard platform
Open the Google cloud SDK console
Change your directory to the folder you have created in the above step
Deploy the application by running the following codes. For more information on how to deploy a python app on app engine standard platform please refer this video given below:
https://www.youtube.com/watch?v=jWRtX8vs_cM
1. gcloud app deploy
2.gcloud app deploy cron.yaml
Find your crons in App Engine Task Queues on your Google Cloud Platform Console
You can explicitly start a job or wait for the time specified in your cron.yaml file to fire the job.