This page shows how to use kubectl to list all of the Container images for Pods running in a cluster.
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using Minikube, or you can use one of these Kubernetes playgrounds:
To check the version, enter kubectl version
.
In this exercise you will use kubectl to fetch all of the Pods running in a cluster, and format the output to pull out the list of Containers for each.
kubectl get pods --all-namespaces
-o jsonpath={..image}
. This will recursively parse out the
image
field from the returned json.
Format the output using standard tools: tr
, sort
, uniq
tr
to replace spaces with newlinessort
to sort the resultsUse uniq
to aggregate image counts
kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c
The above command will recursively return all fields named image
for all items returned.
As an alternative, it is possible to use the absolute path to the image
field within the Pod. This ensures the correct field is retrieved
even when the field name is repeated,
e.g. many fields are called name
within a given item:
kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}"
The jsonpath is interpreted as follows:
.items[*]
: for each returned value.spec
: get the spec.containers[*]
: for each container.image
: get the imageNote: When fetching a single Pod by name, for examplekubectl get pod nginx
, the.items[*]
portion of the path should be omitted because a single Pod is returned instead of a list of items.
The formatting can be controlled further by using the range
operation to
iterate over elements individually.
kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}' |\
sort
To target only Pods matching a specific label, use the -l flag. The
following matches only Pods with labels matching app=nginx
.
kubectl get pods --all-namespaces -o=jsonpath="{..image}" -l app=nginx
To target only pods in a specific namespace, use the namespace flag. The
following matches only Pods in the kube-system
namespace.
kubectl get pods --namespace kube-system -o jsonpath="{..image}"
As an alternative to jsonpath, Kubectl supports using go-templates for formatting the output:
kubectl get pods --all-namespaces -o go-template --template="{{range .items}}{{range .spec.containers}}{{.image}} {{end}}{{end}}"
Was this page helpful?
Thanks for the feedback. If you have a specific, answerable question about how to use Kubernetes, ask it on Stack Overflow. Open an issue in the GitHub repo if you want to report a problem or suggest an improvement.