20

With command, I can add label as below

kubectl label pod POD_NAME KEY1=VALUE1

How could I do that from kubernetes API?

I guess it can be done by PATCH /api/v1/namespaces/{namespace}/pods/{name}

Here is pod.json

{
    "apiVersion": "v1",
    "kind": "Pod",
    "metadata": {
        "labels": {
            "key1": "value1"
        }
    }
}

I tried with following command

KUBE_TOKEN=$(</var/run/secrets/kubernetes.io/serviceaccount/token)
curl --request PATCH --insecure \
      --header "Authorization: Bearer $KUBE_TOKEN"  \
      --data "$(cat pod.json)" \
      https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/$POD_NAMESPACE/pods/$POD_NAME

And it returns

{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {},
  "status": "Failure",
  "message": "the server responded with the status code 415 but did not return more information",
  "details": {},
  "code": 415
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Mr.Wang from Next Door
  • 13,670
  • 12
  • 64
  • 97

2 Answers2

15

Set content-type to application/json-patch+json and specify the patch in http://jsonpatch.org format.

$ cat > patch.json <<EOF
[ 
 { 
 "op": "add", "path": "/metadata/labels/hello", "value": "world" 
 } 
]
EOF
$ curl --request PATCH --data "$(cat patch.json)" -H "Content-Type:application/json-patch+json" https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/$POD_NAMESPACE/pods/$POD_NAME  
Eric Tune
  • 7,819
  • 1
  • 15
  • 17
  • `Content-Type: application/merge-patch+json` works for me – Mr.Wang from Next Door Mar 23 '16 at 10:43
  • 1
    I have done this to add simple labels like: "hello=world", in the example above. But, can you use this approach to add a label like: "domain.com/hello=world"? "path":"/metadata/labels/domain.com/hello" doesn't seem to work, nor do various methods I've tried to escape the "/" in "domain.com/hello". – David McKinley Nov 07 '16 at 23:47
  • Have you tried merge patch. Search for merge in https://github.com/kubernetes/kubernetes/blob/master/docs/devel/api-conventions.md – Eric Tune Nov 12 '16 at 17:53
  • 1
    @DavidMcKinley, If you need to refer to a key with `~` or `/` in its name, you must replace them by `~0` and `~1` respectively. So for your example `"path":"/metadata/labels/domain.com~1hello"` – Merlijn Sebrechts May 06 '19 at 11:38
0

In order to use JSON Patch properly, you have to set content type to application/json-patch+json as defined in RFC6902. Works for me.

Lionel
  • 1