0

Let's suppose I have this python script main.py:

import sys
if not sys.argv[1]:
    print('Empty')
    sys.exit()
print('Otherwise')

If I run it like this python3 main.py '', it prints Empty

If I run it like this python3 main.py 45, it prints Otherwise

Now let's say I'm going to build a Docker image that runs this script. This is my Dockerfile:

FROM python:3.6-slim
ARG A_VARIABLE

WORKDIR /
COPY main.py /

RUN python3 main.py ${A_VARIABLE}

If I build my image using this command docker build --build-arg A_VARIABLE=45 . it's working fine.

Sending build context to Docker daemon  1.905MB
Step 1/5 : FROM python:3.6-slim
 ---> c36a97a24d09
Step 2/5 : ARG A_VARIABLE
 ---> Using cache
 ---> e9146c21f196
Step 3/5 : WORKDIR /
 ---> Using cache
 ---> 942a7511c60d
Step 4/5 : COPY main.py /
 ---> Using cache
 ---> 96bd3882233a
Step 5/5 : RUN python3 main.py ${A_VARIABLE}
 ---> Using cache
 ---> 4c9f0b1b997c
Successfully built 4c9f0b1b997c

If I build it like this docker build --build-arg A_VARIABLE='' . it fails.

Sending build context to Docker daemon  1.905MB
Step 1/5 : FROM python:3.6-slim
 ---> c36a97a24d09
Step 2/5 : ARG A_VARIABLE
 ---> Using cache
 ---> e9146c21f196
Step 3/5 : WORKDIR /
 ---> Using cache
 ---> 942a7511c60d
Step 4/5 : COPY main.py /
 ---> Using cache
 ---> 96bd3882233a
Step 5/5 : RUN python3 main.py ${A_VARIABLE}
 ---> Running in e1b5dab971d2
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    if not sys.argv[1]:
IndexError: list index out of range
The command '/bin/sh -c python3 main.py ${A_VARIABLE}' returned a non-zero code: 1

Is there any workaround for this so that I can pass empty values as build-args?

About me
  • 31
  • 4

2 Answers2

0

In the shell (and thus in a Dockerfile RUN statement) an unquoted empty variable simply disappears.

RUN python3 main.py "${A_VARIABLE}"

See also When to wrap quotes around a shell variable?

tripleee
  • 175,061
  • 34
  • 275
  • 318
-1
import sys
if len(sys.argv) > 1:
    print('Empty')
    sys.exit()
print('Otherwise')

In python code instead of using argv[1], check the length of array of command line arguments passed. That way, you can pass empty arguments in docker command.