【问题标题】:List all resources in a namespace using the Kubernetes python client使用 Kubernetes python 客户端列出命名空间中的所有资源
【发布时间】:2020-08-30 10:08:01
【问题描述】:

使用 kubectl 可以获取 Kubernetes 命名空间内的完整资源列表,但速度极慢。这很容易做到,但对于我需要做的事情来说太慢了。

我更喜欢使用 python or golang clients 来完成 kubectl 代表我所做的事情。但是the API docs are, well, generated by a machine,除了另一台机器之外别无用处:-) 你会认为会有这样简单的例子,但可惜没有。

我知道使用 kubectl 和 scotch tape 以及 bash shell 可以执行以下操作:

#! /bin/bash

NAMESPACE=${1:-default}

kubectl get ns $NAMESPACE  > /dev/null 2>&1 || {
   echo $0: Namespace $NAMESPACE was not found >&2
   exit 1
}

for type in $(kubectl  api-resources -o name --namespaced=true --no-headers --verbs=list)
do
  for item in $(kubectl -n $NAMESPACE get $type --ignore-not-found --show-kind --no-headers -o name | grep -v events.k8s.io | grep -v event)
  do
    echo $item
  done
done

如何使用适用于 kubernetes 的非常程序化的 python 客户端来完成这项工作?

【问题讨论】:

    标签: python kubernetes client


    【解决方案1】:

    也许这就是你要找的东西:

    from kubernetes import client, config
    
    
    # Configs can be set in Configuration class directly or using helper utility
    config.load_kube_config()
    
    v1 = client.CoreV1Api()
    for api in client.ApisApi().get_api_versions().groups:
        versions = []
        for v in api.versions:
            name = ""
            if v.version == api.preferred_version.version and len(
                    api.versions) > 1:
                name += "*"
            name += v.version
            versions.append(name)
        print("%-40s %s" % (api.name, ",".join(versions)))
    

    取自这里:https://github.com/kubernetes-client/python/blob/master/examples/api_discovery.py

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2021-10-24
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2016-04-24
      • 2020-11-06
      相关资源
      最近更新 更多