21

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
}

2 Answers 2

16

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  
Sign up to request clarification or add additional context in comments.

4 Comments

Content-Type: application/merge-patch+json works for me
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".
Have you tried merge patch. Search for merge in github.com/kubernetes/kubernetes/blob/master/docs/devel/…
@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"
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.