Python googleapiclient of `kubectl get deployments`?



我正在尝试从cli kubernetes命令转移到基于Python的google API,以检索GKE集群的信息。

具体来说,我想列出所有部署。在kubectl,我这样做:

kubectl get deployments

我找不到使用googleapiclient/discovery的在线等效程序。有人知道在Python中实现这一点的首选方法是什么吗?

我知道我可以像这样找到关于我的集群的信息:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
'key.json')
service = discovery.build('container', 'v1', credentials=credentials)
project = 'my-project'
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']))
print("%s" % (cluster))

这样尝试:

from google.oauth2 import service_account
from google.cloud.container_v1 import ClusterManagerClient
from kubernetes import client
import google.auth.transport.requests
project_id = "my-project"
zone = "my-zone"
cluster_id = "my-cluster"
credentials = service_account.Credentials.from_service_account_file( 'key.json')
# Get GKE cluster details for the given cluster.
cluster_manager_client = ClusterManagerClient(credentials=credentials)
cluster = cluster_manager_client.get_cluster(
project_id=project_id, zone=zone,
cluster_id=cluster_id)
# Get a token with the scopes required by GKE
kubeconfig_creds = credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/userinfo.email'])
auth_req = google.auth.transport.requests.Request()
kubeconfig_creds.refresh(auth_req)
#Client below is the k8s-client.
configuration = client.Configuration()
# the enpoint is an ip address, so we can't use the SSL verification :(
configuration.host = "https://"+cluster.endpoint+":443"
configuration.verify_ssl = False
kubeconfig_creds.apply(configuration.api_key)
client.Configuration.set_default(configuration)
#Use any kubernetes client methods, here I get all the deployments
deployments = client.AppsV1Api().list_deployment_for_all_namespaces()
for d in deployments.items:
...

最新更新