DEV Community

Mesrar
Mesrar

Posted on

Kubernetes Essentials: Labels, Selectors, Environment Variables, and Annotations Demystified

Labels: Organizing and Identifying Kubernetes Resources

Viewing Labels
To display labels for pods, deployments, or all resources, use:

kubectl get po|deploy|all --show-labels
Enter fullscreen mode Exit fullscreen mode

Adding Labels to Resources
Add labels to a pod, deployment, or node:

kubectl label po <pod-name> <label-key>=<label-value>
kubectl label deploy <deployment-name> <label-key>=<label-value>
kubectl label no <node-name> <label-key>=<label-value>
Enter fullscreen mode Exit fullscreen mode

Removing Labels
Remove a label from a pod:

kubectl label po <pod-name> <label-key>-
Enter fullscreen mode Exit fullscreen mode

Overwriting Labels
Overwrite a label for a pod:

kubectl label po <pod-name> <label-key>=<new-label-value> --overwrite
Enter fullscreen mode Exit fullscreen mode

Important Notes
Duplicate keys are not allowed in labels.

Selectors: Filtering Resources Based on Labels

Filtering Resources
Filter pods based on labels:

kubectl get po --selector=<label-key>=<label-value>

Enter fullscreen mode Exit fullscreen mode

Inequality and Multiple Labels
Use inequality and multiple labels in selectors:

kubectl get po --selector=<label-key>!=<label-value>
kubectl get po --selector=<label-key>=<label-value>,<label-key>=<label-value>
Enter fullscreen mode Exit fullscreen mode

Environment Variables: Configuring Pods
Creating Pods with Environment Variables
Run an nginx pod with an environment variable:

kubectl run nginx --image=nginx --env=app=web

Enter fullscreen mode Exit fullscreen mode

Important Properties
env and envFrom properties are arrays.
env property takes name and value properties.

Annotations: Adding Metadata to Resources

Adding Annotations to Pods
Annotate a pod with additional information:

kubectl annotate po <pod-name> <annotation-key>=<annotation-value>

Enter fullscreen mode Exit fullscreen mode

Removing Annotations
Remove an annotation from a pod:

kubectl annotate po <pod-name> <annotation-key>-

Enter fullscreen mode Exit fullscreen mode

Important Notes

Duplicate keys are not allowed in annotations.

Enhance your Kubernetes resource organization with labels, leverage selectors for efficient filtering, configure environment variables for pods, and add valuable metadata using annotations.

Happy Kuberneting!

Top comments (0)