How to get the annotations using the kubernetes API for python?

Viewed 313

I have a Docker image that contains an application in python, running in Kubernetes as a deployment, I want to pass to that application some data. I used env vars but I would like to use annotations but I'm not sure how to read them, I saw that V1ObjectMeta has a field called annotations but I'm a bit lost of how to call it.

For example:

If my pod has this:

template:
  metadata:
    annotations:
      foo: "var"

How to read foo: var using the python program that is running inside the pod using the Kubernetes library?

1 Answers

All you need is to get the pod object from Kubernetes API. It has the same structure as in YAML format, so once you have the data, the rest is trivial. See below:

from kubernetes import client, config

config.load_incluster_config()
c = client.CoreV1Api()

pod = c.read_namespaced_pod(name="my-pod-name", namespace="my-namespace")

print(pod.metadata.annotations["foo"])
Related