Listing all resources in a namespace

◇◆丶佛笑我妖孽 提交于 2019-12-02 18:56:52
rcorre

Based on this comment , the supported way to list all resources is to iterate through all the api versions listed by kubectl api-resources:

kubectl api-resources enumerates the resource types available in your cluster.

this means you can combine it with kubectl get to actually list every instance of every resource type in a namespace:

kubectl api-resources --verbs=list --namespaced -o name \
  | xargs -n 1 kubectl get --show-kind --ignore-not-found -l <label>=<value> -n <namespace>

I ended up needing this same functionality due to failed Helm deployments that left remnants in a specific namespace. Here's a function you can put in your bash profile:

function kubectlgetall {
  for i in $(kubectl api-resources --verbs=list --namespaced -o name | grep -v "events.events.k8s.io" | grep -v "events" | sort | uniq); do
    echo "Resource:" $i
    kubectl -n ${1} get --ignore-not-found ${i}
  done
}

Usage: kubectlgetall <namespace>

Example: get all resources from the kafka namespace:

kubectlgetall kafka

All kubernetes objects are stored in etcd.

All objects are stored in ETCD v3 the following way:

/registry/<object_type>/<namespace>/<name>

I suggest just to take the list of all resources of some namespace from etcd v3 directly:

ETCDCTL_API=3 etcdctl --endpoints=<etcd_ip>:2379 get / --prefix --keys-only | grep -E "^/\w+/\w+/<namespace>/+"

A Powershell implementation of rcorre's answer would look like

kubectl api-resources --verbs=list --namespaced -o name | `
%{ kubectl get $_ --show-kind --ignore-not-found -l <label>=<value> -n <namespace> }

Answer of rcorre is correct but for N resources it make N requests to cluster (so for a lot of resources this approach is very slow). Moreover, not found resources (that have not instances) are very slow for getting with kubectl get.

There is a better way to make a request for multiple resources:

kubectl get pods,svc,secrets

instead of

kubectl get pods
kubectl get svc
kubectl get secrets

So the answer is:

#!/usr/bin/env bash

# get all names and concatenate them with comma
NAMES="$(kubectl api-resources \
                 --namespaced \
                 --verbs list \
                 -o name \
           | tr '\n' ,)"

# ${NAMES:0:-1} -- because of `tr` command added trailing comma
# --show-kind is optional
kubectl get "${NAMES:0:-1}" --show-kind

or

#!/usr/bin/env bash

# get all names
NAMES=( $(kubectl api-resources \
                  --namespaced \
                  --verbs list \
                  -o name) )

# Now join names into single string delimited with comma
# Note *, not @
IFS=,
NAMES="${NAMES[*]}"
unset IFS

# --show-kind is enabled implicitly
kubectl get "$NAMES"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!