OpenShift – kubectl get custom output using JSONPath and custom-columns.

Sometimes we may want to get custom output from oc/kubectl commands when looking for k8 cluster objects like namespace, pods, etc.

POCGuru k8s OpenShift

In this article, we will explain how to use JSONPath or custom column options to customize the kubectl output. We will use ‘service’ as an example.

1. JSONPath Query

JSONPath is a query language for JSON, and it provides desired flexibility to query JSON output for K8 object.

Example: List all services running in OpenShift cluster and get output as csv file (should work for any k8).

Bash
$oc get svc -Ao jsonpath='{range.items[*]}{@.metadata.name}{","}{@.metadata.namespace}{","}{@.spec.type}{","}{@.spec.ports[*].port}{"\n"}{end}' --sort-by=.metadata.name

alertmanager-main,openshift-monitoring,ClusterIP,9094 9092 9097
alertmanager-operated,openshift-monitoring,ClusterIP,9093 9094 9094
api,openshift-apiserver,ClusterIP,443 
api,openshift-oauth-catalog-operator-metrics,openshift-operator-lifecycle-manager,ClusterIP,8443
kubectl get custom output using JSONPath
kubectl get custom output using JSONPath

2. kubectl custom column

Another less ‘customizable’ option is to use -o custom-columns option with kubectl.

Bash
$oc get svc -Ao custom- columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace --sort- by=.metadata.name
custom-columns option with kubectl
custom-columns option with kubectl

JSONPath query provides flexibility, and can be useful to create custom reports etc., but kubectl on the other hand can be easy to use if looking for standard outputs.

Thank you.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.