Google cloud: Get GKE stats using python API

9/13/2019

In order e.g. to get the number of nodes in a GKE cluster, you need to:

  • use glcoud command to switch to the appropriate project
  • use gcloud command to get the credentials for the cluster in the likes of
gcloud container clusters get-credentials "${CLUSTER_NAME}" --zone "${ZONE}" --project "${PROJECT_ID}"

(but after explicitly passing the zone)

Assuming I am powerful enough, is there a way to get e.g. the number of nodes for a GKE cluster just by iterating over the projects and then the clusters, e.g.

for project in gcp_projects:
   clusters = get_clusters(project)
   for cluster in clusters:
      nodes = get_number_of_nodes(cluster)
-- pkaramol
api
google-cloud-platform
google-kubernetes-engine
python

1 Answer

9/15/2019

The following Python 3 script will print all clusters with the current node count in multiple projects (specified in the variable gcp_projects), in all zones (zone = '-' in the query means all zones) :

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

service = discovery.build('container', 'v1', credentials=credentials)

gcp_projects = ['project-1', 'project-2', 'project-3']

for project in gcp_projects:
    request = service.projects().zones().clusters().list(projectId=project, zone='-')
    response = request.execute()

    if 'clusters' in response:
        for cluster in response['clusters']:
            print("%s,%s,%d" % (project, cluster['name'], cluster['currentNodeCount']))

Sample result (project,clusterName,currentNodeCount) :

project1,cluster1-in-project1,3
project1,cluster2-in-project1,2
project2,cluster1-in-project2,6

This example is based on the example provided in the documentation of projects.locations.clusters.list API.

-- norbjd
Source: StackOverflow