How to pass as environment variable the digest of the Docker image used to the container, in Kubernetes

1/31/2019

I am running a Docker image using Kubernetes. I would like to pass to the container the digest of the image being used. So that the code inside the container can use this for debugging/logging. The problem is that I do not seem to be able to find a way to do this without hard-coding the image digest into the pod configuration.

Is there a way to define pod configuration way so that it dynamically passes the digest as environment variable for whichever version of Docker image it ends up using?

-- Mitar
docker
kubernetes

1 Answer

1/31/2019

Whatever Kubernetes happens to know can be injected using the downward API. That set of data is in the API reference for Pod objects.

It looks like this should work:

env:
  - name: DOCKER_IMAGE_ID
    valueFrom:
      fieldRef:
        fieldPath: status.containerStatuses[0].imageID

You may prefer to inject the spec.containers[0].image name, which will be easier to understand after the fact. If you're using a tool like Helm to generate the configuration, you can also use its values system:

image: {{ .Values.image }}:{{ .Values.tag }}
env:
  - name: DOCKER_IMAGE_TAG
    value: {{ .Values.tag }}
-- David Maze
Source: StackOverflow