'Docker build command using Buildkit secrets fails in Gitlab

My Dockerfile (somewhat redacted here) looks like this:

FROM python:3.9.9-slim-bullseye

WORKDIR /tmp


RUN --mount=type=secret,id=token echo "$(cat /run/secrets/token)" >> /tmp/token

COPY entrypoint.sh /
ENTRYPOINT [ "/entrypoint.sh" ]

Now, when I run the following docker build command:

DOCKER_BUILDKIT=1 docker build --progress=plain --secret id=token,src=$TOKEN -f Dockerfile .

in a gitlab job, it fails with the error:

could not parse secrets: [id=token,src=xyz]: failed to stat xyz: stat xyz: no such file or directory

I tried to replace "src" with "env", but I get the following error:

could not parse secrets: [id=token,env=xyz]: unexpected key 'env' in 'env=xyz'

I've tried setting # syntax=docker/dockerfile:1.2 at the top of dockerfile, but still no luck. The exact same command works on my workstation, it's only on Gitlab that it isn't working.

Not sure what I'm missing here.



Solution 1:[1]

env option on --secret added in the newer versions of docker. If you want to read the secret content from env, you can use process substitution like <(echo $TOKEN):

DOCKER_BUILDKIT=1 docker build --progress=plain --secret id=token,src=src=<(echo $TOKEN) -f Dockerfile .

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 meshkati