Skip to content

Instantly share code, notes, and snippets.

@mpolatcan
Created October 30, 2019 22:12
Show Gist options
  • Save mpolatcan/063ed00895c716cd8ce57d385352165a to your computer and use it in GitHub Desktop.
Save mpolatcan/063ed00895c716cd8ce57d385352165a to your computer and use it in GitHub Desktop.
Google Kubernetes API Client to manage Google Kubernetes Engine Cluster written in Python
import base64
import json
from google.oauth2.service_account import Credentials
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes.client import ApiClient, CoreV1Api
from kubernetes.client.configuration import Configuration as KubernetesClientConfiguration
from tempfile import NamedTemporaryFile
class KubernetesApiClient:
def __init__(self, service_account_str, project_id, zone, cluster_id, scopes=["https://www.googleapis.com/auth/cloud-platform"]):
self.__sa_credentials = Credentials.from_service_account_info(
json.loads(service_account_str), scopes=scopes
)
self.__cluster_info = ClusterManagerClient(credentials=self.__sa_credentials).get_cluster(
project_id=project_id, zone=zone, cluster_id=cluster_id
)
def create(self):
config = KubernetesClientConfiguration()
with NamedTemporaryFile(mode="w", delete=False) as cert:
cert.write(base64.b64decode(self.__cluster_info.master_auth.cluster_ca_certificate).decode("utf-8"))
config.ssl_ca_cert = cert.name
config.host = "https://{endpoint}".format(endpoint=self.__cluster_info.endpoint)
config.api_key_prefix["authorization"] = "Bearer"
config.api_key["authorization"] = self.__sa_credentials.token
return ApiClient(config)
if __name__ == "__main__":
client = KubernetesApiClient(
service_account_str=open("YOUR_SERVICE_ACCOUNT_FILENAME.json", "r").read(-1),
project_id="YOUR_PROJECT_ID",
zone="YOUR_CLUSTER_ZONE",
cluster_id="YOUR_CLUSTER_ID"
).create()
core_v1 = CoreV1Api(api_client=client)
pods = core_v1.list_pod_for_all_namespaces(watch=False)
print("Listing pods with their IPs:")
for pod in pods.items:
print("%s\t%s\t%s" % (pod.status.pod_ip, pod.metadata.namespace, pod.metadata.name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment