Search code examples
kuberneteskubernetes-servicekubernetes-python-client

What is the API equivalent for adding/deleting kubernetes annotations?


I'm trying to find the API equivalent of How to remove (delete) annotation in Kubernetes to remove annotation for a service type in Python. Doing it from the command line works perfectly fine.

The latest kubernetes-client/python does not have any APIs that allow to patch annotations. I could always delete and recreate the service, but I'd like to patch it.

This is a simple MCVE if someone wants. A test service YAML

apiVersion: v1
kind: Service
metadata:
  name: my-service
  annotations:
    description: my test service
spec:
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

and the Python code I'm using

from kubernetes import client, config
from kubernetes.client.rest import ApiException

config.load_kube_config()

coreV1 = client.CoreV1Api()
appsV1 = client.AppsV1Api()

try:
    resp = coreV1.read_namespaced_service("my-service", "default")
    del resp.metadata.annotations["description"]
    patch = coreV1.patch_namespaced_service("my-service", "default", body=resp)
    print(patch)

except ApiException as e:
     print(str(e))

Solution

  • An annotation is part of the overall metadata for a resource. The API functions are related to patching the resource, not the annotation specifically.

    The Kubernetes API documents a PATCH to a Service which equates to patch_namespaced_service in the python API. The JSON required to delete an annotation is:

    {
      "metadata": {
        "annotations": {
          "your/thing": null
        }
      }
    }
    

    Python will serialise None to null

    coreV1.patch_namespaced_service("my-service", "default", body={
      "metadata":{"annotations":{"description": None}}
    })
    

    For any operation, the cli can output the REST calls and "Request Body" if you increase the log level verbosity with kubectl -v8:

    I1112 05:34:08.910667   10552 request.go:1097] Request Body: {"metadata":{"annotations":{"your/thing":null}}}
    I1112 05:34:08.910771   10552 round_trippers.go:420] PATCH https://k8s:6443/api/v1/namespaces/default/services/kubernetes?fieldManager=kubectl-annotate