List all objects from a given namespace using kubectl - kubernetes

I would like to list all objects that are present in a specific namespace in kubernetes.
kubectl get all -n <namespace>
the above command doesn't list all available objects from the given namespace. Is there a way to list them using kubectl?
i can list all objects that i want by passing them to kubectl. but i dont want that.
kubectl -n <namespace> get deployment,rs,sts,ds,job,cronjobs -oyaml

First of all these following rules decide if the resource will be part of the all Category or not.
Here are the rules to add a new resource to the kubectl get all output.
No cluster scoped resources
No namespace admin level resources (limits, quota, policy,
authorization rules)
No resources that are potentially unrecoverable (secrets and pvc)
Resources that are considered "similar" to #3 should be grouped the
same (configmaps)
To Answer your question This is taken from rcorre's Answer
kubectl api-resources --verbs=list --namespaced -o name \
| xargs -n 1 kubectl get --show-kind --ignore-not-found -l <label>=<value> -n <namespace>
Lastly, If you want to add a Custom Resource in all category, you need to provide these field in your CRD spec. custom-resource-definitions:categories
# categories is a list of grouped resources the custom resource belongs to.
categories:
- all

Perhaps you could try this:
kubectl get `kubectl api-resources -o name | tr '\n' ',' | sed 's/.$//'`
Source : Github

Try:
kubectl -n your_namespace get all

Related

is it possible to get all pods from a list of namescapes?

I have a lot of namespaces and I want to get all pods from a sub-list of namespaces.
For getting all the pods from all namespace the command is:
kubectl get pods --all-namespaces
To get all pods from a spesific namespace the command is:
kubectl get pods -n namespace-name
However I can't find a way to get all pods from a list of namespaces, something like:
kubectl get pods -n namespace-name1, namespace-name2, namespace-name3
what is the right command for that?
kubectl does not support this. You can use egrep to filter the list of all pods by namespaces:
kubectl get pods -A | egrep '^(namespace-name1|namespace-name2|namespace-name3)'
Because kubectl prints the namespace at the beginning of the line, it greps for a line start ^ followed by one of the namespace names.
You can iterate over the subset of namespaces:
Either:
for NAMESPACE in "namespace-1" "namespace-2"
do
kubectl get pods \
--namespace=${NAMESPACE} \
--output=name
done
Or:
NAMESPACE=$(
"namespace-1"
"namespace-2"
)
for NAMESPACE in "${NAMESPACES[#]}"
do
kubectl get pods \
--namespace=${NAMESPACE} \
--output=name
done

How to get the pods from the namespaces with a particular label?

It is possible to get all the pods on the cluster:
kubectl get pod --all-namespaces -o wide
It is also possible to get all pods on the cluster with a specific label:
kubectl get pod --all-namespaces -o wide --selector some.specific.pod.label
It is even possible to get all pods on the specific node of the cluster:
kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>
The question is, how to get all pods from the namespaces with a particular label?
e.g. kubectl get pod --namespace-label some.specific.namespace.label -o wide (pseudocode)
One cannot do that operation in one shot, because labels on Namespace objects are not propagated down upon their child objects. Since kubectl is merely doing a GET on /api/v1/whatevers there is no obvious way to make a REST request to two endpoints at once and join them together.
You'll want either a for loop in shell, or to use one of the many API client bindings to create a program that does the Namespace fetch, then a Pod fetch for those matching Namespaces; for example:
for n in $(kubectl get ns --selector some.specific.namespace.label -o name); do
# it's possible kubectl -n will accept the "namespace/foo" output of -o name
# or one can even -o go-template='{{ range .items }}{{ .metadata.name }} {{ end }}'
n=${n##namespace/}
kubectl -n "$n" get pods -o wide
done

Listing all resources in a namespace

I would like to see all resources in a namespace.
Doing kubectl get all will, despite of the name, not list things like services and ingresses.
If I know the the type I can explicitly ask for that particular type, but it seems there is also no command for listing all possible types. (Especially kubectl get does for example not list custom types).
Any idea how to show all resources before for example deleting that namespace?
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>
This may not get all resources but it may be what someone is looking for
kubectl get all,cm,secret,ing -A
This seems to get most of the resources, prefixed with the type.
At least, it gets:
pod
service
daemonset
deployment
replicaset
statefulset
job
configmap
secret
ingress
This doesn't get custom resources but does get services.
Else this does something similar:
for i in `kubectl api-resources | awk '{print $1}'`; do kubectl get $i; done
Running v1.13
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
if [ -z "$1" ]
then
kubectl get --ignore-not-found ${i}
else
kubectl -n ${1} get --ignore-not-found ${i}
fi
done
}
Usage: kubectlgetall <namespace>
Example: get all resources from the kafka namespace:
kubectlgetall kafka
Complete solution
kubectl -n <NAMESPACE> get $(kubectl api-resources --namespaced=true --no-headers -o name | egrep -v 'events|nodes' | paste -s -d, - ) --no-headers
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"
If you are using kubectl krew plug-in, I will suggest using get-all.
It can get almost 90% of resources. Including configmap, secret, endpoints, istio, etc...
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> }
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>/+"
Just covering some basics:
Resources can be fetched using the kubectl get command.
Resources can be filtered by namespace using the -n [NAMESPACE] or --namespace [NAMESPACE] flags.
I will use the -A (same as --all-namespaces) flag in the following examples for brevity.
Some of the other answers show how to list available resource types:
kubectl api-resources --verbs=list -o name
With this in mind, we can get all resources, leveraging xargs and sed:
kubectl get "all,$(kubectl api-resources --verbs=list -o name | xargs | sed 's/ /,/g')" -A
An alternative to xargs is to use tr:
kubectl get "$(kubectl api-resources --verbs=list -o name | tr '\n' ',')all" -A
I think this could be se simplest way to print out all the resource name in a kubernetes cluster:
#!/bin/bash
for resource in [$(kubectl api-resources -o name | tr "\n" " ")]
do
kubectl get $resource --all-namespaces -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}'
done
to specify the namespace you just need to modify the line in the loop setting --namespace=<your-namespace> and remove --all-namespaces
Here's a PowerShell version of what other's have said
function getall {
# https://stackoverflow.com/questions/47691479/listing-all-resources-in-a-namespace
[CmdletBinding()]
param(
$namespace
)
$types=kubectl api-resources --verbs=list --namespaced -o name
kubectl get $($types -join ",") -n $namespace --show-kind
}
It's not a 100% solution, but for me works the following
kgetall='kubectl get namespace,replicaset,secret,nodes,job,daemonset,statefulset,ingress,configmap,pv,pvc,service,deployment,pod --all-namespaces'
and just call
kgetall
But obviously I expected that behavior from
kubectl get all --all-namespaces
in the first place.
Following this solution, in fish shell it looks like below.
Add the following function to your ~/.config/fish/config.fish
function kall
kubectl -n $argv get (string join ',' (kubectl api-resources --namespaced --verbs list -o name))
end
the easy way for me to retrieve all the contents of the namespace was
kubectl get all -n

How do you cleanly list all the containers in a kubernetes pod?

I am looking to list all the containers in a pod in a script that gather's logs after running a test. kubectl describe pods -l k8s-app=kube-dns returns a lot of info, but I am just looking for a return like:
etcd
kube2sky
skydns
I don't see a simple way to format the describe output. Is there another command? (and I guess worst case there is always parsing the output of describe).
Answer
kubectl get pods POD_NAME_HERE -o jsonpath='{.spec.containers[*].name}'
Explanation
This gets the JSON object representing the pod. It then uses kubectl's JSONpath to extract the name of each container from the pod.
You can use get and choose one of the supported output template with the --output (-o) flag.
Take jsonpath for example,
kubectl get pods -l k8s-app=kube-dns -o jsonpath={.items[*].spec.containers[*].name} gives you etcd kube2sky skydns.
Other supported output output templates are go-template, go-template-file, jsonpath-file. See http://kubernetes.io/docs/user-guide/jsonpath/ for how to use jsonpath template. See https://golang.org/pkg/text/template/#pkg-overview for how to use go template.
Update: Check this doc for other example commands to list container images: https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/
Quick hack to avoid constructing the JSONpath query for a single pod:
$ kubectl logs mypod-123
a container name must be specified for pod mypod-123, choose one of: [etcd kubesky skydns]
I put some ideas together into the following:
Simple line:
kubectl get po -o jsonpath='{range .items[*]}{"pod: "}{.metadata.name}{"\n"}{range .spec.containers[*]}{"\tname: "}{.name}{"\n\timage: "}{.image}{"\n"}{end}'
Split (for readability):
kubectl get po -o jsonpath='
{range .items[*]}
{"pod: "}
{.metadata.name}
{"\n"}{range .spec.containers[*]}
{"\tname: "}
{.name}
{"\n\timage: "}
{.image}
{"\n"}
{end}'
How to list BOTH init and non-init containers for all pods
kubectl get pod -o="custom-columns=NAME:.metadata.name,INIT-CONTAINERS:.spec.initContainers[*].name,CONTAINERS:.spec.containers[*].name"
Output looks like this:
NAME INIT-CONTAINERS CONTAINERS
helm-install-traefik-sjts9 <none> helm
metrics-server-86cbb8457f-dkpqm <none> metrics-server
local-path-provisioner-5ff76fc89d-vjs6l <none> local-path-provisioner
coredns-6488c6fcc6-zp9gv <none> coredns
svclb-traefik-f5wwh <none> lb-port-80,lb-port-443
traefik-6f9cbd9bd4-pcbmz <none> traefik
dc-postgresql-0 init-chmod-data dc-postgresql
backend-5c4bf48d6f-7c8c6 wait-for-db backend
if you want a clear output of which containers are from each Pod
kubectl get po -l k8s-app=kube-dns \
-o=custom-columns=NAME:.metadata.name,CONTAINERS:.spec.containers[*].name
To get the output in the separate lines:
kubectl get pods POD_NAME_HERE -o jsonpath='{range .spec.containers[*]}{.name}{"\n"}{end}'
Output:
base-container
sidecar-0
sidecar-1
sidecar-2
If you use json as output format of kubectl get you get plenty details of a pod. With json processors like jq it is easy to select or filter for certain parts you are interested in.
To list the containers of a pod the jq query looks like this:
kubectl get --all-namespaces --selector k8s-app=kube-dns --output json pods \
| jq --raw-output '.items[].spec.containers[].name'
If you want to see all details regarding one specific container try something like this:
kubectl get --all-namespaces --selector k8s-app=kube-dns --output json pods \
| jq '.items[].spec.containers[] | select(.name=="etcd")'
Use below command:
kubectl get pods -o=custom-columns=PodName:.metadata.name,Containers:.spec.containers[*].name,Image:.spec.containers[*].image
To see verbose information along with configmaps of all containers in a particular pod, use this command:
kubectl describe pod/<pod name> -n <namespace name>
Use below command to see all the information of a particular pod
kubectl get pod <pod name> -n <namespace name> -o yaml
For overall details about the pod try following command to get the container details as well
kubectl describe pod <podname>
I use this to display image versions on the pods.
kubectl get pods -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{end}{end}' && printf '\n'
It's just a small modification of script from here, with adding new line to start next console command on the new line, removed commas at the end of each line and listing only my pods, without service pods (e.g. --all-namespaces option is removed).
There are enough answers here but sometimes you want to see a deployment object pods' containers and initContainers. To do that;
1- Retrieve the deployment name
kubectl get deployment
2- Retrieve containers' names
kubectl get deployment <deployment-name> -o jsonpath='{.spec.template.spec.containers[*].name}'
3- Retrieve initContainers' names
kubectl get deployment <deployment-name> -o jsonpath='{.spec.template.spec.initContainers[*].name}'
Easiest way to know the containers in a pod:
kubectl logs -c -n

Command to delete all pods in all kubernetes namespaces

Upon looking at the docs, there is an API call to delete a single pod, but is there a way to delete all pods in all namespaces?
There is no command to do exactly what you asked.
Here are some close matches.
Be careful before running any of these commands. Make sure you are connected to the right cluster, if you use multiple clusters. Consider running. kubectl config view first.
You can delete all the pods in a single namespace with this command:
kubectl delete --all pods --namespace=foo
You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace
kubectl delete --all deployments --namespace=foo
You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command:
kubectl delete --all namespaces
However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable.
This command will delete all the namespaces except kube-system, which might be useful:
for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
kubectl delete ns $each
done
kubectl delete daemonsets,replicasets,services,deployments,pods,rc,ingress --all --all-namespaces
to get rid of them pesky replication controllers too.
You can simply run
kubectl delete all --all --all-namespaces
The first all means the common resource kinds (pods, replicasets, deployments, ...)
kubectl get all == kubectl get pods,rs,deployments, ...
The second --all means to select all resources of the selected kinds
Note that all does not include:
non namespaced resourced (e.g., clusterrolebindings, clusterroles, ...)
configmaps
rolebindings
roles
secrets
...
In order to clean up perfectly,
you could use other tools (e.g., Helm, Kustomize, ...)
you could use a namespace.
you could use labels when you create resources.
You just need sed to do this:
kubectl get pods --no-headers=true --all-namespaces |sed -r 's/(\S+)\s+(\S+).*/kubectl --namespace \1 delete pod \2/e'
Explains:
use command kubectl get pods --all-namespaces to get the list of all pods in all namespaces.
use --no-headers=true option to hide the headers.
use s command of sed to fetch the first two words, which represent namespace and pod's name respectively, then assemble the delete command using them.
the final delete command is just like:
kubectl --namespace kube-system delete pod heapster-eq3yw.
use the e modifier of s command to execute the command assembled above, which will do the actual delete works.
To avoid delete pods in kube-system namespace, just need to add grep -v kube-system to exclude kube-system namespace before the sed command.
I tried commands from listed answers here but pods were stuck in terminating state.
I found below command to delete all pods from particular namespace if stuck in terminating state or you are not able to delete it then you can delete pods forcefully.
kubectl delete pods --all --grace-period=0 --force --namespace namespace
Hope it might be useful to someone.
K8s completely works on the fundamental of the namespace. if you like to release all the resource related to specified namespace.
you can use the below mentioned :
kubectl delete namespace k8sdemo-app
steps to delete pv:
delete all deployment and pods or resources related to that PV
kubectl delete --all deployment -n namespace
kubectl delete --all pod -n namespace
edit pv
kubectl edit pv pv_name -n namespace
remove kubernetes.io/pv-protection
delete pv
kubectl delete pv pv_name -n namespace
Delete all PODs in all Namespace only (restart deployment)
kubectl get pod -A -o yaml | kubectl delete -f -
You can use kubectl delete pods -l dev-lead!=carisa or what label you have.
Here is a one-liner that can be extended with grep to filter by name.
kubectl get pods -o jsonpath="{.items[*].metadata.name}" | \
tr " " "\n" | \
xargs -i -P 0 kubectl delete pods {}
One line command to delete all pods in all namespaces.
kubectl get ns -o=custom-columns=Namespace:.metadata.name --no-headers | xargs -n1 kubectl delete pods --all -n
kubectl delete po,ing,svc,pv,pvc,sc,ep,rc,deploy,replicaset,daemonset --all -A
If you already have pods which are recreated, think to delete all deployments first
kubectl delete -n *NAMESPACE deployment *DEPLOYMENT
Just replace the NAMSPACE and the DEPLOYMENT to corresponding ones, you can get all deployments information by the following command
kubectl get deployments --all-namespaces
Kubectl bulk (bulk-action on krew) plugin may be useful for you, it gives you bulk operations on selected resources. This is the command for deleting pods
' kubectl bulk pods -n namespace delete '
You could check details in this
I create a python code to delete all in namespace
delall.py
import json,sys,os;
obj=json.load(sys.stdin);
for item in obj["items"]:
os.system("kubectl delete " + item["kind"] + "/" +item["metadata"]["name"] + " -n yournamespace")
and then
kubectl get all -n kong -o json | python delall.py
If you have multiple pod which are crashing or error and you want to delete them
kubectl delete pods --all -n | gep
It was hinted at above, but I just thought I would helpfully point out that the shortcut for "--all-namespaces" is "-A" that's with a capital A. HTH somebody. I've opened a PR to have this helpful hint added to the official Kubernetes Cheat Sheet.
If you want to delete pods in all namespaces just to have them restarted and you are aware that some of them will be recreated, I like the following for loop:
for i in $(kubectl get pods -A | awk '{print $1}' | uniq | grep -V NAMESPACE); do kubectl delete --all pods -n $i; done
if you have hpa, then scale down.