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

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).
$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

2. kubectl custom column
Another less ‘customizable’ option is to use -o custom-columns
option with kubectl
.
$oc get svc -Ao custom- columns=NAME:.metadata.name,NAMESPACE:.metadata.namespace --sort- by=.metadata.name

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.