Retrieve pod description(kubectl describe) from the output of other expression - kubernetes

In kubectl, describe and get -o can be used to get the details of a resource, can we get a describe of only a list of selected pods (different labels), my case is to details of selected pod names for analysis. I'm using describe but unable to get details of specific pods, there are quite a few to do it manually.
If it was events/ specific labels, i could do the below but need more specific details of certain pods out of 100 of them
kubectl get describe po -l app2=test > desc.txt
Kubectl get events -n test|grep -E 'app2|app3|hello1' > events.txt
Tried the below it returns the events of all pods in the namespace (doesnt help), any simpler way or may be this cannot be done or write a script to loop through the o/p?
kubectl get po -n test |grep -E 'app2|app3|hello1' |awk '{print $1}'|k describe po -n test > desc.txt
Thanks for the help!

Are you saying you can't use labels?
Not sure I understand correctly but if you need to choose pods by name - this will work:
kubectl get pod -oname | grep -E 'app2|app3|hello' | xargs kubectl describe

Related

searching for a keyword in all the pods/replicas of a kuberntes deployment

I am running a deployment called mydeployment that manages several pods/replicas for a certain service. I want to search all the service pods/instances/replicas of that deployment for a certain keyword. The command below defaults to one replica and returns the keyword matching in this replica only.
Kubectl logs -f deploy/mydeployment | grep "keyword"
Is it possible to customize the above command to return all the matching keywords out of all instances/pods of the deployment mydeployment? Any hint?
Save this to a file fetchLogs.sh file, and if you are using Linux box, use sh fetchLogs.sh
#!/bin/sh
podName="key-word-from-pod-name"
keyWord="actual-log-search-keyword"
nameSpace="name-space-where-the-pods-or-running"
echo "Running Script.."
for podName in `kubectl get pods -A -o name | grep -i ${podName} | cut -d'/' -f2`;
do
echo "searching pod ${podName}"
kubectl -n ${nameSpace} logs pod/${podName} | grep -i ${keyWord}
done
I used the pods, if you want to use deployment, the idea is same change the kubectl command accordingly.

How to get the list of pods with container name for pods that have restarted

Using this command, I am able to get the container name that have restarted.
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[?(#.restartCount>0)].name}'
Is there a way to get the pod name as well in the same command?
It's much easier to get json with kubectl and then process it with jq :
#!/usr/bin/env bash
kubectl get pods -o=json |
jq -r '.items[] |
"\(.metadata.name) \(.status.containerStatuses[]|select(.restartCount>0).name)"'
I've not tried this.
If (!) it works, it's not quite what you want as it should give you every Pod name and then a list of Container names that match the predicate.
I think you can't use kubectl --output=jsonpath alone to filter only the Pod names that have a Container with restarts.
FILTER='
{range .items[*]}
{.metadata.name}
{"\t"}
[
{.status.containerStatuses[?(#.restartCount>0)].name}
]
{"\n"}
{end}
'
kubectl get pods \
--output=jsonpath="${FILTER}"

Get count of Kubernetes pods that aren't running

I've this command to list the Kubernetes pods that are not running:
sudo kubectl get pods -n my-name-space | grep -v Running
Is there a command that will return a count of pods that are not running?
If you add ... | wc -l to the end of that command, it will print the number of lines that the grep command outputs. This will probably include the title line, but you can suppress that.
kubectl get pods -n my-name-space --no-headers \
| grep -v Running \
| wc -l
If you have a JSON-processing tool like jq available, you can get more reliable output (the grep invocation will get an incorrect answer if an Evicted pod happens to have the string Running in its name). You should be able to do something like (untested)
kubectl get pods -n my-namespace -o json \
| jq '.items | map(select(.status.phase != "Running")) | length'
If you'll be doing a lot of this, writing a non-shell program using the Kubernetes API will be more robust; you will generally be able to do an operation like "get pods" using an SDK call and get back a list of pod objects that you can filter.
You can do it without any external tool:
kubectl get po \
--field-selector=status.phase!=Running \
-o go-template='{{len .items}}'
the filtering is done with field-selectors
the counting is done with go-template: {{ len .items }}

How to kubectl wait for crd creation?

What is the best method for checking to see if a custom resource definition exists before running a script, using only kubectl command line?
We have a yaml file that contains definitions for a NATS cluster ServiceAccount, Role, ClusterRoleBinding and Deployment. The image used in the Deployment creates the crd, and the second script uses that crd to deploy a set of pods. At the moment our CI pipeline needs to run the second script a few times, only completing successfully once the crd has been fully created. I've tried to use kubectl wait but cannot figure out what condition to use that applies to the completion of a crd.
Below is my most recent, albeit completely wrong, attempt, however this illustrates the general sequence we'd like.
kubectl wait --for=condition=complete kubectl apply -f 1.nats-cluster-operator.yaml kubectl apply -f 2.nats-cluster.yaml
The condition for a CRD would be established:
kubectl -n <namespace-here> wait --for condition=established --timeout=60s crd/<crd-name-here>
You may want to adjust --timeout appropriately.
In case you are wanting to wait for a resource that may not exist yet, you can try something like this:
{ grep -q -m 1 "crontabs.stable.example.com"; kill $!; } < <(kubectl get crd -w)
or
{ sed -n /crontabs.stable.example.com/q; kill $!; } < <(kubectl get crd -w)
I understand the question would prefer to only use kubectl, however this answer helped in my case. The downside to this method is that the timeout will have to be set in a different way and that the condition itself is not actually checked.
In order to check the condition more thoroughly, I made the following:
#!/bin/bash
condition-established() {
local name="crontabs.stable.example.com"
local condition="Established"
jq --arg NAME $name --arg CONDITION $condition -n \
'first(inputs | if (.metadata.name==$NAME) and (.status.conditions[]?.type==$CONDITION) then
null | halt_error else empty end)'
# This is similar to the first, but the full condition is sent to stdout
#jq --arg NAME $name --arg CONDITION $condition -n \
# 'first(inputs | if (.metadata.name==$NAME) and (.status.conditions[]?.type==$CONDITION) then
# .status.conditions[] | select(.type==$CONDITION) else empty end)'
}
{ condition-established; kill $!; } < <(kubectl get crd -w -o json)
echo Complete
To explain what is happening, $! refers to the command run by bash's process substitution. I'm not sure how well this might work in other shells.
I tested with the CRD from the official kubernetes documentation.

What command can I run to get the oldest pod's name?

I want to get the name of the oldest pod as part of a script. It seems like I should be able to run kubectl get po --no-headers=true, sort-by AGE, and then just pipe to head -n1|awk '{print $1}', but I can't seem to get sort-by working. I'm running kubectl 1.7.9.
The AGE times are in an irregular format (23m, 2d) that’s hard to sort on, but you can ask kubectl to write out the time a pod started instead. The times will come out in the very sortable ISO 8601 format. This recipe to get the single oldest pod might work for you:
kubectl get pods \
--no-headers \
--output=custom-columns=START:.status.startTime,NAME:.metadata.name \
| sort \
| head -1 \
| awk '{print $2}'
The kubectl command asks to only print out the start time and name, in that order, for each pod.
Also consider kubectl get pods -o json, which will give you a very large very detailed JSON record. If you have a preferred full-featured scripting language you can pick that apart there, or use a command-line tool like jq to try digesting it further. Any field path can also be inserted into the custom-columns output spec.
This can be accomplished with:
kubectl get pods --sort-by=.metadata.creationTimestamp -o=name | head -1
I'm not sure what version this started work in, but I'm using it in kubectl 1.12.