0

Using kubectl, it's possible, but extremely slow to get a complete list of resources within a Kubernetes namespace. This is easy enough to do, but too slow for what I need to do.

I'd prefer to use the python or golang clients to do what kubectl is doing on my behalf. But the API docs are, well, generated by a machine, and good for nothing other than another machine :-) You'd think there'd be an example for something this simple, but alas, there isn't.

I know that using kubectl and scotch tape and bash shell that I can do the following:

#! /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

How would this be done using the very procedural python client for kubernetes?

1 Answers1

2

Maybe this is what you were looking for:

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)))

Taken from here: https://github.com/kubernetes-client/python/blob/master/examples/api_discovery.py