28

I've found jsonpath examples for testing multiple values but not extracting multiple values.

I want to get image and name from kubectl get pods.

this gets me name kubectl get pods -o=jsonpath='{.items[*].spec.containers[*].name}' | xargs -n 1

this gets me image kubectl get pods -o=jsonpath='{.items[*].spec.containers[*].image}' | xargs -n 1

but kubectl get pods -o=jsonpath='{.items[*].spec.containers[*].[name,image}' | xargs -n 2

complains invalid array index image - is there a syntax for getting a list of node-adjacent values?

navicore
  • 1,979
  • 4
  • 34
  • 50

3 Answers3

40

Use below command to get name and image:

kubectl get pods -Ao jsonpath='{range .items[*]}{@.metadata.name}{" "}{@.spec.template.spec.containers[].image}{"\n"}{end}'

It will give output like below:

name image
freeo
  • 3,509
  • 1
  • 22
  • 17
Pawan Kumar
  • 830
  • 1
  • 9
  • 15
  • 4
    thx! works for me with a minor tweak: `kubectl get pods -ao jsonpath='{range .items[*]}{@.metadata.name}{" "}{@.spec.containers[*].image}{"\n"}{end}'` – navicore Sep 15 '17 at 01:02
6

Useful command, I had to modify it a little to make it work (failed with -a flag). Also, I added a filter to app label and one more field to get: namespace, pod name, image

kubectl get pods --all-namespaces -o jsonpath='{range .items[*]}{@.metadata.namespace}{"\t"}{@.metadata.name}{"\t"}{@.spec.containers[*].image}{"\n"}{end}' -l app=nginx
Gonzalo Cao
  • 2,286
  • 1
  • 24
  • 20
  • -a should have been -A for all namespaces. ```kubectl get pods -Ao jsonpath='{range .items[*]}{@.metadata.name}{" "}{@.spec.containers[*].image}{"\n"}{end}'``` – Dobhaweim May 06 '22 at 10:05
2

Thanks! I had to change a little bit, but this worked for me:

#!/bin/bash

releases=$(kubectl get deployment -A --output=jsonpath='{range .items[*]}{@.metadata.namespace}{"|"}{@.metadata.name}{"\n"}{end}')

for release in $releases; do
    namespace=$( echo $release | cut -d "|" -f 1)
    deployment=$( echo $release | cut -d "|" -f 2)
    kubectl rollout restart deployments -n "${namespace}" "${deployment}"
done