Kubectl Tip: Filtering Output with Custom Columns

If you work with CI/CD tools, there may be use cases where you need to customize the kubectl output, maybe for a report or an HTML output.

I had a similar requirement and made use of the kubectl custom columns feature. I think you'll like it too.

By default, kubectl provides a list of default headers with its output.

You can modify the default kubectl output headers and data using custom columns.

The kubectl get command has a flag named --custom-columns that allows you to customize the output in the format you prefer.

Practical Example

Now lets look at some practical examples.

Here is the command that gives custom output showing the pod name and CPU & memory requests. For a specific namespace add the -n <namespace> to the command.

$ kubectl get pod -o custom-columns='PODNAME:.metadata.name,CPU REQUEST:.spec.containers[*].resources.requests.cpu,MEMORY REQUEST:.spec.containers[*].resources.requests.memory'

You will get an output as shown below

POD NAME                        CPU REQUEST   MEMORY REQUEST

frontend-prod-v1                500m          512Mi
backend-prod-v2                 1             1Gi
database-prod                   2             4Gi
cache-prod                      250m          128Mi
analytics-worker-prod           200m          256Mi

Here is another example that lists the pod name and volumes used by a pod.

$ kubectl get pod -o custom-columns='POD NAME:.metadata.name, VOLUMES:.spec.volumes[*].name'

Example Output

POD NAME               VOLUMES
multi-container-pod   nginx-logs,kube-api-access-56rhl
web-app-01            nginx-logs-1,kube-api-access-8nkwn
web-app-02            nginx-logs-2,kube-api-access-68hgd
web-app-04            nginx-logs-2,kube-api-access-5d6xh

Note: --custom-columns is mainly for human-readable output in a table format. For more complex queries and to extract specific data, use JsonPath with kubectl.

Reply

or to participate.