3

I want to use kubectl get -o=custom-columns to extract information with specific columns. The cropped yaml response is like this

{
    "apiVersion": "v1",
    "items": [
        {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "creationTimestamp": "2018-11-27T14:37:46Z",
                "generateName": "kubernetes-bootcamp-5c69669756-",
                "labels": {
                    "pod-template-hash": "1725225312",
                    "run": "kubernetes-bootcamp"
                },
                "name": "kubernetes-bootcamp-5c69669756-cxhwf",
                "namespace": "default",
                "ownerReferences": [
                    {
                        "apiVersion": "extensions/v1beta1",
                        "blockOwnerDeletion": true,
                        "controller": true,
                        "kind": "ReplicaSet",
                        "name": "kubernetes-bootcamp-5c69669756",
                        "uid": "950aac8e-f24f-11e8-bf5d-065b6ba59aa8"
                    }
                ],
                "resourceVersion": "118035",
                "selfLink": "/api/v1/namespaces/default/pods/kubernetes-bootcamp-5c69669756-cxhwf",
                "uid": "0190c234-f252-11e8-bf5d-065b6ba59aa8"
            },

I want to extract the name from items[0].metadata.name, but I don't know the syntax.

My questions:

  1. What is the query syntax used in this situation. Is it JSON path? I don't see it documented.
  2. What is the specific query in my case?

3 Answers 3

2

Since the result is JSON, pipe the result to jq and go from there.

kubectl get | jq '.items[0].metadata.name'

yields

➜ cat abc.json | jq '.items[0].metadata.name'
"kubernetes-bootcamp-5c69669756-cxhwf"
0

The syntax of the command is as follows;

$ kubectl get pods <optional_pod_name> --output custom-columns="NAME:.metadata.name"
NAME
kubernetes-bootcamp-5c69669756-cxhwf

You can add more columns by separating them with commas. For example;

$ kubectl get pods <optional_pod_name> -o custom-columns="NAME:.metadata.name,STATUS:.status.phase"

NAME                                   STATUS
kubernetes-bootcamp-5c69669756-cxhwf   Running
0

You can also use JSONPath:

kubectl get nodes --output=custom-columns='$COLUMN_NAME:$JSON_PATH'
kubectl get nodes --output=custom-columns='NAME:{.metadata.name}' # optional curly bracket
kubectl get nodes --output=custom-columns='NAME:.metadata.name,POD_CIDR:{.spec.podCIDR}'
kubectl get nodes --output=jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.podCIDR}{"\n"}{end}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.