Kubernetes get the full pod name as environment variable

9/25/2019

I know that I can define something like this to get the pod name in my containers:

env:
- name: POD_NAME
  valueFrom:
     fieldRef:
       fieldPath: metadata.name

But when I run: $kubectl get pods

I have a different result, something like: uipod-5d6795db87-cxxkg which corresponds to <replicatset name>-cxxkg.

Is it possible to get that full name (uipod-5d6795db87-cxxkg) as environnement variable? Instead of only the pod name (uipod).

Thanks a lot

-- akuma8
kubectl
kubernetes
kubernetes-pod

1 Answer

9/25/2019

You don't need to explicitly set environment variable with pod name, its already present inside pod as an environment variable called HOSTNAME.

For example

$ kubectl run nginx --image=nginx
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectlrun --generator=run-pod/v1 or kubectl create instead.
deployment.apps/nginx created
$
$ kubectl get pods
NAME                     READY   STATUS    RESTARTS   AGE
nginx-7bb7cd8db5-kddbs   1/1     Running   0          12s
$
$ kubectl exec -it nginx-7bb7cd8db5-kddbs bash
root@nginx-7bb7cd8db5-kddbs:/#
root@nginx-7bb7cd8db5-kddbs:/# env | grep HOSTNAME
HOSTNAME=nginx-7bb7cd8db5-kddbs
root@nginx-7bb7cd8db5-kddbs:/#

NOTE: As you can see HOSTNAME environment variable already have the exact pod name set.

-- mchawre
Source: StackOverflow