Is there a way to get all namespace scoped resource objects by label selector using python kubernetes client?

755 views Asked by At

I want to achieve this command use kubernetes python client.

kubectl -n namespace get all -l key=value

I've seen several questions here List all resources in a namespace using the Kubernetes python client

but it's means

kubectl api-resources

not what I want.

I can't find an example case, so what is the right way to do this?

1

There are 1 answers

1
Aref Riant On

namespaced resources in Kubernetes api is structured like:

/api/v1/namespaces/{namespace}/pods
/api/v1/namespaces/{namespace}/secrets
/api/v1/namespaces/{namespace}/services
.
.
.

just for resources accessible by Core API

to have access to other resources like StatefulSets, you need to use Apps API

at the end of the day, you need to name all resources you need to retrieve,

from kubernetes import client, config
config.load_kube_config()
v1 = client.CoreV1Api()
namespace = "default"

pods = v1.list_namespaced_pod(namespace)
services = v1.list_namespaced_service(namespace)
# And continue for all resources accessible by core api...


appv1 = client.AppsV1Api()
statefulsets = appv1.list_namespaced_stateful_set(namespace)
# And continue for all resources

You can use get_api_resources() to list all resource names possible, and then iterate over them like the code above, inform in the comments if you needed help.