<p>I'm attempting to inject a ReplicationController's randomly generated pod ID extension (i.e. <code>multiverse-{replicaID}</code>) into a container's environment variables. I could manually get the hostname and extract it from there, but I'd prefer if I didn't have to add the special case into the script running inside the container, due to compatibility reasons.</p>

<p>If a pod is named <code>multiverse-nffj1</code>, <code>INSTANCE_ID</code> should equal <code>nffj1</code>. I've scoured the docs and found nothing.</p>

<pre><code>apiVersion: v1
kind: ReplicationController
metadata:
  name: multiverse
spec:
  replicas: 3
  template:
    spec:
      containers:
      - env:
        - name: INSTANCE_ID
          value: $(replicaID)
</code></pre>

<p>I've tried adding a <code>command</code> into the controller's template configuration to create the environment variable from the hostname, but couldn't figure out how to make that environment variable available to the running script.</p>

<p>Is there a variable I'm missing, or does this feature not exist? If it doesn't, does anyone have any ideas on how to make this to work without editing the script inside of the container?</p>

<p>There is an <a href="https://stackoverflow.com/a/49649009/9521610">answer</a> provided by <a href="https://stackoverflow.com/users/5937420/anton-kostenko">Anton Kostenko</a> about inserting DB credentials into container environment variables, but it could be applied to your case also. It is all about the content of the InitContainer spec.</p>

<p>You can use <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/" rel="nofollow noreferrer"><strong>InitContainer</strong></a> to get the hash from the container’s hostname and put it to the file on the shared volume that you mount to the container.   </p>

<p>In this example <strong>InitContainer</strong> put the Pod name into the <code>INSTANCE_ID</code> environment variable, but you can modify it according to your needs: </p>

<p>Create the <em>init.yaml</em> file with the content:</p>

<pre><code>apiVersion: v1
kind: Pod
metadata:
  name: init-test
spec:
  containers:
  - name: init-test
    image: ubuntu
    args: [bash, -c, 'source /data/config &amp;&amp; echo $INSTANCE_ID &amp;&amp; while true ; do sleep 1000; done ']
    volumeMounts:
    - name: config-data
      mountPath: /data
  initContainers:
  - name: init-init 
    image: busybox
    command: ["sh","-c","echo -n INSTANCE_ID=$(hostname) &gt; /data/config"]
    volumeMounts:
    - name: config-data
      mountPath: /data
  volumes:
  - name: config-data
    emptyDir: {}
</code></pre>

<p>Create the pod using following command:</p>

<pre><code>kubectl create -f init.yaml
</code></pre>

<p>Check if Pod initialization is done and is Running:</p>

<pre><code>kubectl get pod init-test
</code></pre>

<p>Check the logs to see the results of this example configuration:</p>

<pre><code>$ kubectl logs init-test
init-test
</code></pre>
