initContainers to set pod name from node name

Created: — modified: — tags: k8s

This is actually surprisingly easy

Just add this to your pod spec:

      initContainers:
        - name: set-hostname
          image: busybox:latest
          securityContext:
            runAsUser: 0
            capabilities:
              add: ["SYS_ADMIN"]
          env:
            - name: NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
          command: ['sh', '-c', 'hostname "$NODE_NAME"']

Trick here is to note that result of hostname call "survives" between separate container runs in the same pod, and also this way you don't have to modify securityContext or command of your main pod(s).