Page Content

Tutorials

What are Kubernetes Annotations and Use Cases with Example

Kubernetes annotations

Pods, Services, and Deployments can have arbitrary, non-identifying metadata appended using Kubernetes annotations. Labels identify and select items, while annotations provide context and descriptions for tools, libraries, and human operators. Despite this, they have a similar key-value pair structure. Annotations are essentially the “baggage” meant to contain supplementary data utilized by external systems or the Kubernetes control plane itself, whereas labels are essentially “nametags” for grouping resources.

Kubernetes Objects

In Kubernetes, objects are the basic building blocks that symbolize the intended cluster state. The desired state includes the containers that should be operating, the nodes on which they should be operating, the resources that should be utilized for those containers, and additional characteristics like fault tolerance, upgrades, and policies. See this GeeksforGeeks article: Kubernetes-Services for additional information about Kubernetes Objects.

Kubernetes Metadata

The Kubernetes configuration file’s metadata section includes Labels, Resources, and Attributes. The container details display this metadata in the user interface.The two most common types of information in Kubernetes configuration files are “name” and “label”. The example is as follows. See Kubernetes – Deployments for additional information regarding Kubernetes deployment.Concept annotations are even used by Kubernetes replica-sets.

Kubernetes Metadata includes the following:

  1. Kubernetes Attributes
  2. Resources
  3. Labels

How to write annotations syntax:

"metadata": {
  "annotations": {
    "key1" : "value1",
    "key2" : "value2"
  }
}

You can also read How to install Kubectl in Kubernetes Explained Briefly

Syntax and character set 

Annotations are key-value pairs. Valid annotation keys separate the optional prefix and name with a slash (/). Name segments must start and finish with alphanumeric letters ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics in between. Use 63 characters or less. Prefixes are optional. The prefix must be a DNS subdomain, a string of DNS labels separated by dots (.) and no more than 253 characters followed by a slash.

If the prefix is omitted, the annotation Key is presumed to be private to the user. Automated system components (e.g. kube-schedulerkube-controller-managerkube-apiserverkubectl, or other third-party automation) which add annotations to end-user objects must specify a prefix.

The kubernetes.io/ and k8s.io/ prefixes are reserved for Kubernetes core components.

For example, here’s a manifest for a Pod that has the annotation imageregistry: https://hub.docker.com/ :

apiVersion: v1
kind: Pod
metadata:
name: annotations-demo
annotations:
imageregistry: "https://hub.docker.com/"
spec:
containers:
name: nginx
image: nginx:1.14.2
ports:
containerPort: 80

How to Use (kubectl):

  • Add/Update: kubectl annotate pods <pod-name> key=value
  • Overwrite: kubectl annotate --overwrite pods <pod-name> key=new-value
  • Remove: kubectl annotate pods <pod-name> key- (trailing dash removes it) 

You can also read Kubernetes Controller Manager vs Cloud Controller Manager

Primary Use Cases and Examples

Annotations are utilized across a wide spectrum of Kubernetes operations, ranging from administrative tracking to advanced infrastructure orchestration.

  • Change Tracking and Auditing: One of the most common uses is recording the “change-cause” of a deployment update. By adding the kubernetes.io/change-cause annotation to a Deployment template, administrators can maintain a human-readable history that appears when running commands like kubectl rollout history.
  • Rollout Management: The kubectl apply command uses annotations to record the last-applied configuration. This allows Kubernetes to perform “smart merges” by comparing the new manifest with the previous state stored in the annotation.
  • Infrastructure Extensions: Cloud providers use annotations to trigger specific behaviors in their underlying hardware. For instance, a Service of type LoadBalancer can be annotated with service.beta.kubernetes.io/aws-load-balancer-internal: "true" to instruct the provider to provision an internal load balancer rather than a public-facing one.
  • Security and Policy: Annotations play a critical role in security configurations. AppArmor profiles are applied to containers via specific annotations in the Pod specification. Similarly, the rbac.authorization.kubernetes.io/autoupdate annotation can be set to false to prevent the API server from overwriting custom changes to built-in ClusterRoles during a restart or upgrade.
  • Tooling Integration: External tools like Ingress controllers use annotations to manage complex routing rules. Annotations like kubernetes.io/ingress.class help the cluster determine which controller should handle a specific Ingress object.
  • UI and Metadata: Annotations can store metadata to enhance the visual experience of a dashboard, such as links to documentation, icon URLs, or contact information for the team responsible for a service.

There are also established conventions for service annotations to ensure readability, such as using a8r.io/owner for GitHub usernames, a8r.io/repository for source links, and a8r.io/bugs for issue trackers.

Managing Annotations via the CLI (kubectl)

The Kubernetes CLI’s kubectl annotate command performs CRUD operations. YAML configuration files can provide annotations under metadata.annotations.

  1. Adding/Creating: To add an annotation to a running resource, the syntax is kubectl annotate <resource-type> <resource-name> <key>=<value>. For example, kubectl annotate pods my-pod build-version=v1.2.4.
  2. Updating: Attempting to update an existing annotation will fail by default to prevent accidental overwrites. To modify an existing value, you must use the --overwrite flag, such as kubectl annotate --overwrite service example description="New Description".
  3. Mass Updates: You can update annotations across multiple resources simultaneously using the --all flag, which targets all resources of a specific type within a namespace.
  4. Deleting: To remove an annotation, append a trailing dash (-) to the key: kubectl annotate pods my-pod build-version-.
  5. Viewing: Annotations can be viewed by running kubectl describe <resource> or by outputting the raw metadata with kubectl get <resource> -o yaml.

You can also read How to Install Kubeadm in Kubernetes Step by Step Guide

System and Tooling Integration

The “glue” that keeps the Kubernetes environment extensible is annotations. The kubectl apply command, which logs the most recent configuration applied as an annotation, is one of the most important system-level applications. Kubernetes does “smart merges” by comparing the present, desired, and prior metadata states.

Ingress controllers use annotations like kubernetes.io/ingress.class to establish complex routing rules and determine which controller handles a given item. AppArmor profiles and other security features depend on particular annotations in the Pod standard.

Strategic Best Practices and Architectural Limitations

Despite their strength, annotations have architectural obligations. Kubernetes API server should not be utilized as a normal database. Brief data points connected to a resource should be annotated. Data should be transferred to a dedicated database if it needs to expand substantially or exist independently.

Additionally, annotations are sometimes regarded as “best-effort” metadata since they can be manually removed by a user at any moment. Without appropriate audit controls, they shouldn’t be trusted as the main source of information for crucial system states. Lastly, administrators must exercise caution to avoid creating a “untyped mess” by saving poorly formatted data because the API server does not evaluate the format or content of annotation strings.

You can also read What is Declarative in Kubernetes? & Key Declaratives

The Fundamental Distinction: Annotations vs. Labels

An essential component of Kubernetes resource management is the differentiation between these two forms of metadata. Label selectors employ labels, which are intended for identification, to group resources for vital functions like network security, replica management, and load balancing. Labels are subject to stringent syntax requirements and size restrictions since they are used for querying, which ensures system performance.

On the other hand, the system never selects or identifies items using annotations. They are made to transport opaque data, either unstructured or structured. An annotation can respond to questions like “What Git commit generated this image?” or “Who should be paged if this service fails?” but a label might respond to questions like “Which Pods are in production?” Adding information as an annotation first and promoting it to a label only when there is a clear requirement to utilize it in a selector query is a frequent strategic guideline.

Conclusion

The platform can interface with a wide range of third-party tools, cloud providers, and custom controllers because to Kubernetes annotations’ adaptable, free-form storage space. Kubernetes maintains a clean, scalable architecture that may increase in complexity with the applications it orchestrates by keeping non-identifying “baggage” apart from the identifying metadata of labels. Annotations are still essential for efficient cluster management and automation, whether they are used to maintain CI/CD git hashes, record team ownership, or activate sophisticated infrastructure capabilities.

You can also read What is Kube-Proxy in Kubernetes and it’s Lifecycle