How to use metadata.namespace to annotate Kubernetes Service?

277 Views Asked by At

In Kubernetes Pod definition I am using metadata.namespace to set up appropriate environgment variable.

apiVersion: apps/v1
kind: Deployment
[...]
  template:
    spec:
      containers:
[...]
          env:
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: LOG_DIR
              value: /logs/$(POD_NAMESPACE)

Is there any similar mechanism to use metadata.namespace to set annotation of the Service?

---
apiVersion: v1
kind: Service
metadata:
  annotations:
    external-dns.alpha.kubernetes.io/hostname: {metadata.namespace}.domain.com
2

There are 2 best solutions below

1
On

Short answer, you can't.

$(VAR_NAME) syntax is used for dependent environment variables, but not in annotations, since annotation is a generic concept, used in all kubernetes objects, and, from k8s point of view, is just a key/value pair attached to resource, without any way to interact with underlying object.

Usually, this should be taken care of by your templating engine, i.e. in Helm, you can use {{ Release.Namespace }} (case sensitive!) to inject current namespace in your resource template.

But if you are dealing with plain k8s manifests, without some external tool, you have to provide full annotations in your files.

1
On

You may try the following YAML file:

---
apiVersion: v1
kind: Service
metadata:
  name: your-service
  namespace: service-namespace
  annotations:
    external-dns.alpha.kubernetes.io/hostname: {metadata.name}.{metadata.namespace}.domain.com

Try to indicate namespace on the metadata.