Trying to write some python scripts to handle our infrastructure in GCP. I found that the Google Cloud Python SDK, does not easily convert into python using __dict__
, and json.dumps()
so I had to do some digging. It took a bit of time but found that we can use the Python proto
library to handle conversion of the Google Cloud Objects to JSON. Here’s an example of listing GKE clusters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
from google.cloud import container_v1 import proto import json def list_gke_clusters(): """ Lists GKE clusters in the specified project. Args: project_id (str): Your GCP project ID. Returns: list: List of GKE clusters. """ project_id = 'myproject' client = container_v1.ClusterManagerClient() request = container_v1.ListClustersRequest( parent=f'projects/{project_id}/locations/-') # List clusters in the specified project response = client.list_clusters(request=request) return response.clusters if __name__ == "__main__": clusters = [] for cluster in list_gke_clusters(): if cluster.resource_labels['type'] == 'automation': clusters.append(json.loads(proto.Message.to_json(cluster))) for cluster in clusters: print(cluster['zone']) |
As you can see using proto.Message.to_json(object)
allowed me to provide json parseable data. Just figured someone else can use this and I wanted to keep a note of it as the solution wasn’t something easily able to be found. Someone also found it works for other GCP objects.
Other methods were also discussed here: https://github.com/googleapis/python-vision/issues/70