I wanted to create a way to easily “turn on” and “turn off” a GKE cluster, via an HTTP link that I could bookmark and hit, even from my iPhone. With GKE, if you set your node pool size to zero, you’re not incurring any charge since Google doesn’t hit you on the master nodes. So I wanted to easily set the pool size up and down. Sure, I could issue a “gcloud container” command, or set up Ansible to do it (which I will do since I want to automate more stuff), but I also wanted to get my feet wet with Cloud Functions and GCP API’s.
In Google Cloud Functions, you simply write your functional code in the main file (main.py), AND include the correct dependencies in the requirements.txt file (for Python). That dependency is represented by the same name of the module you’d use in a “pip install”. The module for managing GKE is “google-cloud-container“.
Now one of the great things about using Cloud Functions is that authorization for all API’s within your project “just happen”. You don’t need to figure out OAuth2 or use API keys. You just need to write the code. If you’re going to use this python code outside of Cloud Functions, you’d need to add some code for that and set an environment to point to your secret json file for the appropriate service account for your project.
Here’s sample code to change your GKE Cluster node pool size.
import google.cloud.container
def startk8s(request):
client = google.cloud.container.ClusterManagerClient()
projectID = '<your-project-id>'
zone = 'us-east1-d' """ your zone obviously """
clusterID = '<your-cluster-name>'
nodePoolID = 'default-pool' """ or your pool name """
client.set_node_pool_size(projectID, zone, clusterID, nodePoolID, 3)
return "200"
You need to set the name of the Function you want triggered:

Notice the import statement- “google.cloud.container”. Now you can’t exactly “pip install” into a Cloud Function, it’s not your Python instance! That’s where the dependency.txt file comes in. (There’s a version of that for node.js – package.json, since you can’t npm install either). Here’s the sample dependency.txt file:
# Function dependencies, for example: # package>=version google-cloud-container
Note that the package version seems to be optional. My code works without it.
You can test the cloud function by clicking on the “testing” sub-menu.
