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

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

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

combine multiple column output in kubectl using custom-columns or jsonpath

This is the output with custom-columns
$ kubectl -n web get pod -ocustom-columns="Name:.metadata.name,Image:.spec.containers[0].image"
Name Image
mysql-0 myrepo.mydomain.com/mysql:5.7
mysql-1 myrepo.mydomain.com/mysql:5.7
mysql-2 myrepo.mydomain.com/mysql:5.7
This is the output with jsonpath for single pod
$ kubectl -n web get pod -o jsonpath="{..metadata.name}:{..spec.containers[0].image}" mysql-0
mysql-0:myrepo.mydomain.com/mysql:5.7
This is the output with jsonpath for multiple pods
$ kubectl -n web get pod -o jsonpath="{..metadata.name}:{..spec.containers[0].image}"
mysql-0 mysql-1 mysql-2:myrepo.mydomain.com/mysql:5.7 myrepo.mydomain.com/mysql:5.7 myrepo.mydomain.com/mysql:5.7
Now how to combine this into a single column or word, something like this, using -ocustom-columns or -ojsonpath
mysql-0=myrepo.mydomain.com/mysql:5.7
mysql-1=myrepo.mydomain.com/mysql:5.7
mysql-2=myrepo.mydomain.com/mysql:5.7
Using kubectl using plain jsonpath:
kubectl get pod -n <namespace> -o jsonpath='{range .items[*]}{.metadata.name}={.spec.containers[*].image}{"\n"}{end}'
Example:
kubectl get pod -n default -o jsonpath='{range .items[*]}{.metadata.name}={.spec.containers[*].image}{"\n"}{end}'
nginx-0=nginx
nginx-1=nginx
nginx-2=nginx
Here range feature is used to loop over all the pods:
{range items[*]} ...<LOGIC HERE>... {end}
Between the range block(As described above), use the jsonpath, notice the = sign is used as per our requirement.
{.metadata.name}={.spec.containers[*].image}{"\n"}

Get all pods except the pods inside kube-system

When I do
kubectl get pods -A
I get all pods, and I always have 17 pods that are not "apps", they belong to namespace kube-system. I would like to have an alias not to print them.
Is there a way to print all pods, excluding a namespace ?
You can accomplish this via field selectors:
kubectl get pods -A --field-selector=metadata.namespace!=kube-system
Additionally, the field selector list can have multiple parameters, separated by , (comma literals), and use == or != to specify additional criteria.
Use --field-selector
kubectl get pods --all-namespaces --field-selector metadata.namespace!=kube-system
more about field selectors here: https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/

List all objects from a given namespace using kubectl

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

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