Kubernetes API : add label to pod

13,247

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  
Share:
13,247

Related videos on Youtube

Mr.Wang from Next Door
Author by

Mr.Wang from Next Door

Updated on September 14, 2022

Comments

  • Mr.Wang from Next Door
    Mr.Wang from Next Door over 1 year

    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
    }
    
  • Mr.Wang from Next Door
    Mr.Wang from Next Door about 8 years
    Content-Type: application/merge-patch+json works for me
  • David McKinley
    David McKinley over 7 years
    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".
  • Eric Tune
    Eric Tune over 7 years
    Have you tried merge patch. Search for merge in github.com/kubernetes/kubernetes/blob/master/docs/devel/…
  • Merlijn Sebrechts
    Merlijn Sebrechts almost 5 years
    @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"