Pythonでgkeのクラスタ認証情報を取得する
Pythonでgkeのクラスタ認証情報を取得する
gcloud container clusters get-credentials
をPythonのGoogle Cloud SDKでやる方法
import base64 from tempfile import NamedTemporaryFile import google.auth import google.auth.transport.requests from google.cloud import container_v1 from kubernetes import client def create_k8s_client() -> client.Configuration: project_id = "your-project-name" zone = "us-central1-b" cluster_name = "your-cluster-name" container_client = container_v1.ClusterManagerClient() response = container_client.get_cluster( name=f"projects/{project_id}/locations/{zone}/clusters/{cluster_name}" ) creds, _ = google.auth.default() auth_req = google.auth.transport.requests.Request() creds.refresh(auth_req) configuration = client.Configuration() configuration.host = f"https://{response.endpoint}" with NamedTemporaryFile(delete=False) as ca_cert: ca_cert.write(base64.b64decode(response.master_auth.cluster_ca_certificate)) configuration.ssl_ca_cert = ca_cert.name configuration.api_key_prefix["authorization"] = "Bearer" configuration.api_key["authorization"] = creds.token return configuration if __name__ == "__main__": config = create_k8s_client() k8s_client = client.BatchV1Api( client.ApiClient(config) ) ret = k8s_client.list_job_for_all_namespaces()
参考
Client for Google Container Engine API — google-cloud-container documentation