how to get objects's metadata name in kubernetes

2/25/2020

I can get all the things of a list of objects, such as Secrets and ConfigMaps.

{
"kind": "SecretList",
"apiVersion": "v1",
"metadata": {
    "selfLink": "/api/v1/namespaces/kube-system/secrets",
    "resourceVersion": "499638"
},
"items": [{
    "metadata": {
        "name": "aaa",
        "namespace": "kube-system",
        "selfLink": "/api/v1/namespaces/kube-system/secrets/aaa",
        "uid": "96b0fbee-f14c-423d-9734-53fed20ae9f9",
        "resourceVersion": "1354",
        "creationTimestamp": "2020-02-24T11:20:23Z"
    },
    "data": "aaa"
}]
}

but I only want the name list, for this example :"aaa". Is there any way?

-- qinghai5060
api
kubernetes
rest

2 Answers

2/25/2020

i think this should work.

kubectl get secretlist -o=jsonpath="{.items[*].metadata.name]}" | grep -v HEAD | head -n1

check link in the below for more info.
https://kubernetes.io/docs/reference/kubectl/jsonpath/

-- m303945
Source: StackOverflow

2/25/2020

Yes, you can achieve it by using jsonpath output. Note that the specification you posted will look quite differently once applied. It will create one Secret object in your kube-system namespace and when you run:

$ kubectl get secret -n kube-system aaa -o json

the output will look similar to the following:

{
    "apiVersion": "v1",
    "kind": "Secret",
    "metadata": {
        "creationTimestamp": "2020-02-25T11:08:21Z",
        "name": "aaa",
        "namespace": "kube-system",
        "resourceVersion": "34488887",
        "selfLink": "/api/v1/namespaces/kube-system/secrets/aaa",
        "uid": "229edeb3-57bf-11ea-b366-42010a9c0093"
    },
    "type": "Opaque"
}

To get only the name of your Secret you need to run:

kubectl get secret aaa -n kube-system -o jsonpath='{.metadata.name}'
-- mario
Source: StackOverflow