Add to configmap pod name in Kubernetes

9/22/2021

I'm trying to figure it out, how to change one string inside configmap in Kubernetes. I have pretty simple configmap:

apiVersion: v1
data:
  config.cfg: |-
    [authentication]
    USERNAME=user
    PASSWORD=password
     
    [podname]
    PODNAME=metadata.podName

kind: ConfigMap
metadata:
  name: name_here

And I need to mount the configmap inside a couple of pods. But PODNAME should be matched to current podname. Is it possible in any another way? thanks!

-- Roman
configmap
kubernetes

2 Answers

9/22/2021

This doesn't answer you question exactly but the pod name normally ends up as the host name inside the pod and can be accessed as a standard environment variable

echo $HOSTNAME
-- Andreas Wederbrand
Source: StackOverflow

9/22/2021

I do not think it could be done with ConfigMap. But you can set environment variables in your pod spec that references a pod fields.

apiVersion: v1
kind: Pod
metadata:
  name: test-ref-pod-name
spec:
  containers:
    - name: test-container
      image: busybox
      command: [ "sh", "-c"]
      args:
      - env | grep PODNAME
      env:
        - name: PODNAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
  restartPolicy: Never

See official documentation: https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/#use-pod-fields-as-values-for-environment-variables

-- Arnaud Develay
Source: StackOverflow