Kubernetes not able to add label to pod - kubernetes

I am unable to add a label to my kubernetes pod. Why is this not working?
$ kubectl describe pods secure-monolith | grep Label
Labels: app=monolith
$ kubectl label pods secure-monolith "secure=enabled"
pod "secure-monolith" labeled
$ kubectl describe pods secure-monolith | grep Label
Labels: app=monolith
$ kubectl label pods secure-monolith "secure=enabled"
'secure' already has a value (enabled), and --overwrite is false
As you can see, it says the label was successfully added, however the label does not appear when "describing" the pod; and it can also not be added again.

You are grepping through the describe output, but only the first line of labels description contains Label string.
Labels output for two labels looks as follows:
Labels: a=b
c=d
So secure=enabled is there, you just filtered it out.

kubectl get pod POD_NAME --show-labels
This command shows all the labels added to the pod

Related

How to delete all the Terminated pods of a kubernetes cluster?

I know how to delete a specific pod:
kubectl -n <namespace> delete pod <pod-name>
Is there a way to delete all the Terminated pods once?
What does terminated pod mean? If you wish to delete finished pods of any jobs in the namespace then you can remove them with a single command:
kubectl -n <namespace> delete pods --field-selector=status.phase==Succeeded
Another approach in Kubernetes 1.23 onwards is to use Job's TTL controller feature:
spec:
ttlSecondsAfterFinished: 100
In your case Terminated status means your pods are in a failed state. To remove them just change the status.phase to Failed state (https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/#PodStatus)
You can pipe 2 commands:
kubectl -n <namespace> get pods --field-selector=status.phase==Succeeded -o custom-columns=NAME:.metadata.name --no-headers | kubectl -n <namespace> delete pods
I don't think there is an 'exec' option to kubectl get (like the CLI tool 'find' for instance).
If the command fits your needs, you can always convert it to an alias or shell function

I want to add/remove a label from all pods running in a given namespace

Using the below command labels can be added to a pod.
kubectl label pod <pod-name> {key1=value1,key2=value2,key3=value3}
What is the best way to add or remove a label, say, [ env: dev ] from all pods running in a given namespace.
...to add or remove a label, say, [ env: dev ] from all pods running
in a given namespace.
Try:
kubectl label pods --namespace <name> --all env=dev # <-- add
kubectl label pods --namespace <name> --all env- # <-- remove

How to get the random pod number provided by Kubernetes

I would like to get and see the random number provided by K8s.
kubectl logs abc-abc-platform-xxxxx dicom-server
Here xxxxx has to be replaced with the random generated number.
Can you let me know which command do I have to execute to find the random number?
If the specific pod has the my-app label, you can find that pod and save it as bash variable:
POD=$(kubectl get pod -l app=my-app -o jsonpath="{.items[0].metadata.name}")
and then execute:
kubectl logs $POD
PS. This will work only if you have 1 pod with that specific label.

List all containers in all pods with status

I am trying to get a list of all non-READY containers in all pods to debug a networking issue in my cluster.
Is it possible to use kubectl to get a clean list of all containers in all pods with their status (READY/..)?
I am currently using
$ kubectl get pods
However, the output can be huge and it can be difficult to know which containers are READY and which ones have issues.
Thanks.
kubectl get pods -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .status.containerStatuses[*]}{.ready}{", "}{end}{end}'
Adapted from this doc: https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/#list-containers-by-pod
Edit to describe what the jsonpath is doing:
From what I understand with the jsonpath, range iterates all of the .items[*] returned by getting the pods. \n is added to split the result to one per line, otherwise the result would come to one line. To see how the rest work, you should choose one of your pods and run:
kubectl get pod podname -o yaml
.metadata.name corresponds to
apiVersion: v1
kind: Pod
metadata:
name: podname
Similarly, .status.containerStatuses[*] corresponds to the list of container statuses that should be towards the bottom.
I've adapted #joshua-oliphant's answer to include container-names:
kubectl get pods -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .status.containerStatuses[*]}{.name}{": "}{.ready}{", "}{end}{end}'
This will display all pods including all containers in the current namespace with their ready-state such as:
pod-name: container-name-a: true, container-name-b: false
Using jq, we can list all pods and their containers' statuses:
kubectl get pods --output=json | jq --raw-output '.items | map([.metadata.name, (.status.containerStatuses | map(.name + ": " + (.ready | tostring)))[]]) | .[] | join("\n ")'
This displays something like this:
pod-1234-auiend
container1: true
container2: false
another-pod-2454-123123:
container1: true
(...)

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