Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes API : add label to pod

Tags:

kubernetes

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
}
like image 830
Mr.Wang from Next Door Avatar asked Mar 22 '16 05:03

Mr.Wang from Next Door


1 Answers

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  
like image 138
Eric Tune Avatar answered Sep 18 '22 03:09

Eric Tune