【问题标题】:Python googleapiclient of `kubectl get deployments`?`kubectl get deployments`的Python googleapiclient?
【发布时间】:2021-03-31 09:50:46
【问题描述】:

我正在尝试从 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))

【问题讨论】:

    标签: python google-kubernetes-engine google-api-client


    【解决方案1】:

    试试这样:

    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:
       ...
    

    【讨论】:

    • 我推荐使用 SSL - stackoverflow.com/a/68098831/714876
    • 如果 cluster-endpoint 是一个 ip 号,SSL verification 将如何工作?
    • 在链接中的评论中添加了有关此的信息!
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2022-11-16
    相关资源
    最近更新 更多