Simple GCP Instance Scheduler (w/ Terraform, Cloud Function)

  • Project: Enter GCP Project here
  • Cron Pattern: Enter cron expression here. The default is set for everyday at 6pm run the job.
  • Label Key: Enter label key. The default is set to “instance-scheduler”
  • Label: Value: Enter label value: The default is set to “enabled”
  • Scheduler Function Bucket: Enter bucket name (must be globally unique). This will store the zip file necessary for the Cloud Function. What is that cloud function going to run on your laptop every time its called? I think not!

  • Cloud Scheduler: This will be where your cron job expression (set in will run.
  • PubSub Topic: Cloud scheduler will trigger based on the expression and will send a message (content of message doesn’t matter for this) to the PubSub topic.
  • Cloud Function: A cloud function will be “subscribed” to the topic. When the topic “publishes” the message sent to it, the function will be invoked. The function will get list of current zones and iterates through each zone looking for an instance that matches the filter. The filter is looking for running instances with matching label key and label value. If an instance matches this filter, it is shut down.
  • IAM Role: In order the the cloud function to have the ability to shut down an instance, it needs permission for the following:
  1. To be able to see all the zones (compute.zones.list)
  2. To be able to see all the instances (compute.instances.list)
  3. To be able to stop an instance (compute.instances.stop)
  • And since best practices dictates to use “least privileged”, it’s best to use a custom role here. The other roles like Computer Admin or Instance Admin are too powerful for this simple little shutdown tool. The terraform in the repo also creates the necessary custom role , service account, and adds the service account as a member to the project with the three specific permissions listed above. (two files — and requirements.txt)

  • There are three functions in this file described below:
  1. Gather_Zones — since this list changes as Cloud Providers expand.
  2. Turn_Instance_Off — to make the API call to turn off the instance when it matches the filter.
  3. Instance_Scheduler_Start — to coordinate it all/handle environment variables.
  • requirements.txt: This file list the two libraries needed for the python logic the work.


Here is the log result after successfully running this:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store