Get Kuberbetes Pod name id as an environment variable

1/27/2022

I am trying to get the id in the pod name as a environment variable in the yaml file:

job-05d93d91-d527-4b06-ad89-593f0350ecd6-jobmanager--1-qfjqf      1/1     Running   0          22m
job-05d93d91-d527-4b06-ad89-593f0350ecd6-taskmanager-66758j5h4d   1/1     Running   0          22m
job-05d93d91-d527-4b06-ad89-593f0350ecd6-taskmanager-66758vsj5q   1/1     Running   0          22m

I want to have "66758vsj5q" and "66758j5h4d" and "qfjqf" as an env variable.

I am able to get the pod name by exposing:

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

but POD_NAME from Expose Pod Information to Containers Through Environment Variables returns the whole pod name. I am actually using ververica platform and following this documentation.

Is it possible to be done?

-- Monika X
apache-flink
kubernetes

1 Answer

1/27/2022

Below are the supported things that you could get with valueFrom.

valueFrom: Source for the environment variable's value. Cannot be used if value is not empty.

EnvVarSource represents a source for the value of an EnvVar.

configMapKeyRef (object)

Selects a key of a ConfigMap.

fieldRef (object)

Selects a field of the pod: supports metadata.name, metadata.namespace, metadata.labels, metadata.annotations, spec.nodeName, spec.serviceAccountName, status.hostIP, status.podIP.

resourceFieldRef (object)

Selects a resource of the container: only resources limits and requests (limits.cpu, limits.memory, limits.ephemeral-storage, requests.cpu, requests.memory and requests.ephemeral-storage) are currently supported.

secretKeyRef (object)

Selects a key of a secret in the pod's namespace

So the way you are trying, it does not work.

The string you are getting from metadata.name is actually already exposed as environment variable with name HOSTNAME.

Knowing the pattern of those names, name-hash you can use shell, or any other tool to get the last part. For example, by parameter expansion or by splitting on the hyphen. It would depend on which context you want to use that value.

apiVersion: batch/v1
kind: Job
metadata:
  name: get-hash
spec:
  ttlSecondsAfterFinished: 100
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: get-hash
          image: busybox
          command: ["sh", "-c"]
          args:
            - |
              echo "the podname is: $HOSTNAME";
              echo "the hash is: ${HOSTNAME##*-}"
$ kubectl create -f get-hash.yaml
$ kubectl logs job.batch/get-hash
the podname is: get-hash-mpf7p
the hash is: mpf7p
-- The Fool
Source: StackOverflow