Patrick
Patrick

Reputation: 585

Kubectl json path select a field with special characters

I want to write a kubectl command to query all the namespace and then collect the value of a specific lable.

{
"apiVersion": "v1",
"items": [
    {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "annotations": {
                "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"annotations\":{},\"labels\":{\"app.kubernetes.io/created-by\":\"testuser\",\"app.kubernetes.io/instance\":\"thisisatest\",\"app.kubernetes.io/name\":\"company\",\"app.kubernetes.io/version\":\"2.5\"},\"name\":\"thisiatest\"}}\n"
            },
            "creationTimestamp": "2022-09-01T13:16:12Z",
            "labels": {
                "app.kubernetes.io/created-by": "testuser",
                ...

I have a version with jq that works.

printf "\ncreated by:\n"
kubectl get namespace -l app.kubernetes.io/name=phoenics -o json | jq '.items [] | .metadata | .labels | ."app.kubernetes.io/created-by"'

But i can't really get a version with jsonpath to work. What am i doing wrong?

printf "\ncreated by: JsonPath\n"
kubectl get namespace -l app.kubernetes.io/name=phoenics -o jsonpath="{range ['items'][*]['metadata']['labels']['app.kubernetes.io/created-by']}{'\n'}{end}"

There is no output. Oh, and i'm working on windows with a git bash.

Upvotes: 0

Views: 4275

Answers (2)

gohm'c
gohm'c

Reputation: 15568

No escape sequence required. Tested with k8s 1.22.12:

$ kubectl get namespace -l kubernetes.io/metadata.name=kube-system -o jsonpath="{range ['items'][*]}{['metadata']['labels']}{['kubernetes.io/metadata.name']}{'\n'}{end}"

$ {"kubernetes.io/metadata.name":"kube-system"}

Upvotes: 0

ericfossas
ericfossas

Reputation: 2206

this should work:

kubectl get namespace -l app.kubernetes.io/name=phoenics \
-o jsonpath="{range .items[*]}{.metadata.labels.app\.kubernetes\.io/created-by}{'\n'}{end}"

Upvotes: 5

Related Questions