How can I extract the kubernetes Service object from JSON returned from kubectl

12/14/2018

Given the kubectl command below, and its response, I want to yank out the Service object. The command will get the current state of all the k8s objects that are created by my deployment descriptor, which is named quotem.yaml.

% kubectl get -f quotem_v2.yaml -o json

    {
        "apiVersion": "v1",
        "items": [
            {
                "apiVersion": "v1",
                "kind": "Service",
                "metadata": {
                    "annotations": {
                        "getambassador.io/config": "---\napiVersion: ambassador/v0\nkind:  Mapping\nname:  qotm_mapping_v2\nprefix: /qotm/\nservice: qotm-v2\nweight: 300\n",
                        "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Service\",\"metadata\":{\"annotations\":{\"getambassador.io/config\":\"---\\napiVersion: ambassador/v0\\nkind:  Mapping\\nname:  qotm_mapping_v2\\nprefix: /qotm/\\nservice: qotm-v2\\nweight: 300\\n\"},\"name\":\"qotm-v2\",\"namespace\":\"default\"},\"spec\":{\"ports\":[{\"name\":\"http-qotm\",\"port\":80,\"targetPort\":\"http-api\"}],\"selector\":{\"app\":\"qotm-v2\"}}}\n"
                    },
                    "creationTimestamp": "2018-12-13T17:53:51Z",
                    "name": "qotm-v2",
                    "namespace": "default",
                    "resourceVersion": "202117",
                    "selfLink": "/api/v1/namespaces/default/services/qotm-v2",
                    "uid": "0cf4a4a5-ff00-11e8-9839-080027ced2f4"
                },
       ......
    }
-- Geoffrey Hendrey
jq
json
kubectl
kubernetes
service

1 Answer

12/14/2018

kubectl get -f quotem_v2.yaml -o json | jq '.items[] | select(.kind=="Service")'

  • The command above usese kubectl get with -o flag to output json
  • Then it uses the jq command line json parser to get the items array, and from the items array, select the elements whose 'kind' attribute matches 'Service'
-- Geoffrey Hendrey
Source: StackOverflow