Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate environment variables in Docker

Tags:

docker

assert

Is there any kind of ASSERT in Docker?

In this specific case I want to be able to validate that an environment variable has been set and force the build to fail if it hasn't.

The code that has caused me issues is:

echo ${LICENSE_KEY} > /etc/license.key

I have been tasked with getting a previous employee's code working correctly and have found that this file was empty. It strikes me that this variable being unset should be fatal for this build script and would have saved me lots of debugging.

From my reading of the Docker docs (since Docker 0.7) I can run a shell command that returns a non zero status and that would cause the build to fail. e.g.

RUN [ ! -z "${LICENSE_KEY}" ]

Though this will cause extra layers and code in the image, that may not be obvious to others that it is just there for debugging/protection and does not explicitly state the reason for the failure when combined with other commands. I was really expecting docker to have something akin to:

ASSERT ${LICENSE_KEY} != ""
like image 998
Martin Avatar asked Mar 06 '23 21:03

Martin


2 Answers

I had a similar problem, and I did something like:

RUN [ ! -z "${LICENSE_KEY}" ] || { echo "License key cannot be empty"; exit 1; } && \
    ... other run commands ...
like image 191
Gautam Avatar answered Mar 14 '23 22:03

Gautam


This is the solution I have used, but an ASSERT that didn't create any layers would be better.

ARG LICENSE_KEY
RUN [ ! -z "${LICENSE_KEY}" ] # Assert LICENSE_KEY is defined

Pass case

Step 2/10 : ARG LICENSE_KEY
 ---> Using cache
 ---> e5fba6cf457c
Step 3/10 : RUN [ ! -z "${LICENSE_KEY}" ] # Assert LICENSE_KEY is defined
 ---> Running in 7e83e02e7372
 Removing intermediate container 7e83e02e7372
 ---> c31d8da7b006

fail case

Step 2/10 : ARG LICENSE_KEY
 ---> Using cache
 ---> e5fba6cf457c
Step 3/10 : RUN [ ! -z "${LICENSE_KEY}" ] # Assert LICENSE_KEY is defined
 ---> Running in 0d10210c8bca
The command '/bin/sh -c [ ! -z "${LICENSE_KEY}" ] # Assert LICENSE_KEY is defined' returned a non-zero code: 1

It definitely creates extra 0 byte layers though. As can be seen from running:

docker history --no-trunc <image>

sha256:fe9<...snip...>   About an hour ago   |1 LICENSE_KEY=some-key /bin/sh -c [ ! -z "${LICENSE_KEY}" ] # Assert LICENSE_KEY is defined    0B
sha256:e5f<...snip...>   About an hour ago   /bin/sh -c #(nop)  ARG LICENSE_KEY                                                              0B                                                                                                                                                
sha256:5e8<...snip...>   4 weeks ago         /bin/sh -c #(nop)  CMD ["/bin/bash"]                                                            0B
like image 43
Martin Avatar answered Mar 14 '23 22:03

Martin