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 }}
Related
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.
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
To simplify, I want to list all the docker images defined in a helm chart.
For eg, let's say I have the following set of templates:
$ helm template jenkins/jenkins
https://charts.jenkins.io/
Then, I want to somehow use kubectl to parse this result so I can apply a filter such as:
kubectl get pods -l k8s-app=kube-dns -o jsonpath={.items[*].spec.containers[*].name}
To return me the list. However, that command is to get pods. Any clue?
EDIT: I found a way:
❯ helm template jenkins/jenkins | kubectl apply -f - --dry-run=client -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort | uniq
bats/bats:1.2.1
jenkins/jenkins:2.263.1
kiwigrid/k8s-sidecar:0.1.275
With one drawback: kubectl needs to be connected to a cluster. I would like to prevent that.
You can use a different jsonpath to get all images:
kubectl get pods -A -o jsonpath="{..image}"
If you just want unique images: kubectl get pods -A -o jsonpath="{..image}" | tr -s '[[:space:]]' '\n' | sort -u.
Substituting -A for the namespace of your chart or manifests.
If you have the manifests on your machine and not deployed, of course, you can just grep: grep 'image: ' *.yml
You can also use Go template syntax:
kubectl get pods -A -o go-template --template="{{range .items}}{{range .spec.containers}}{{.image}} {{end}}{{end}}"
If you have more than one chart in a given namespace, I think grepping would be the best way: helm template some-chart | grep 'image:'
EDIT:
Since this will be running in CI, it would be better to use a little bit of code to avoid potential false positives. This Python script does the trick:
#!/usr/bin/env python3
import sys
import yaml # pip install PyYAML
from nested_lookup import nested_lookup # pip install nested-lookup
template = ""
for line in sys.stdin:
template += line
parts = template.split('---')
for p in parts:
y = yaml.safe_load(p)
matches = nested_lookup("image", y)
if (len(matches)):
print("\n".join(matches))
Usage: helm template jenkins/jenkins | ./this-script.py. It prints out each occurrence of images, so if you only want unique images you'd need to throw all the matches in a list, then unique that before printing (or pipe it to sort -u).
newbie here . I am trying to automate the way to get the nodes that are ready using the following script:
until kubectl get nodes | grep -m 2 "Ready"; do sleep 1 ; done
Is there a better way to do this, specifically i am looking for a way to do this without having to specify the node number?
To get the names of all Ready nodes, use
$ kubectl get nodes -o json | jq -r '.items[] | select(.status.conditions[].type=="Ready") | .metadata.name '
master-0
node-1
node-3
node-x
Basing on the official documentation
You can check your ready nodes by using this command:
JSONPATH='{range .items[*]}{#.metadata.name}:{range #.status.conditions[*]}{#.type}={#.status};{end}{end}' \
&& kubectl get nodes -o jsonpath="$JSONPATH" | grep "Ready=True"
You don't need to specify number of nodes in your command, just use it like this:
until kubectl get nodes | grep -i "Ready"; do sleep 1 ; done
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.