JsonPath querying in kubernetes

JSONPath is a query language for selecting and extracting data from JSON objects or documents. In the context of Kubernetes, JSONPath is used to query and extract specific information from Kubernetes resources in their JSON representation. It's often used in kubectl commands, templates, and scripts to retrieve specific values from Kubernetes resources.

Sample pod yaml file

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: my-nginx
  name: my-nginx
spec:
  containers:
  - image: nginx
    name: my-nginx
    ports:
    - containerPort: 80
  - image: busybox
    name: busy-box
    command: ["sleep"]
    args: ["infinity"]
  - image: alpine
    name: alpine
    command: ["sleep"]
    args: ["infinity"]
  • Get all the container names
    k get pod my-nginx -o=jsonpath={.spec.containers[*].name}

  • Get all the container names using range function
    k get pod my-nginx -o=jsonpath={range .spec.containers[*]}{.name}{"\n"}{end}

  • Use range and get the container images and container ID of each container
    k get pod my-nginx -o=jsonpath='{range .status.containerStatuses[*]}[{.image},{.containerID}]{"\n"}{end}'

References:

official doc: here
Youtube video: here