0

I am trying to set an environment variable for a container that is readable from my python script.

The python script is run via a containerized cron job. When running the script directly in the container, without the cronjob, I am able to read my environment variables.

My Dockerfile is

FROM python:3.7-slim

# install crontab
RUN apt-get update && apt-get -y install -qq cron

# install crontab
ENV TESTING=1

ENV CONTAINER_HOME=/opt/
WORKDIR $CONTAINER_HOME

ADD runner.py .

COPY test-cron /etc/cron.d/test-cron

# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/test-cron

RUN crontab /etc/cron.d/test-cron

RUN touch /var/log/cron.log

CMD cron && tail -f /var/log/cron.log

The cron job that runs the script

# every 1 minutes 
* * * * * cd /opt/ && /usr/local/bin/python runner.py >> /var/log/cron.log 2>&1
# An empty line is required at the end of this file for a valid cron file.

Lastly the script that is run

import os

print(os.environ)

I have also created a minimal example here: https://github.com/AndrewRPorter/python-docker-env.

APorter1031
  • 2,107
  • 6
  • 17
  • 38
  • Cron might empty the environment. See https://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables for a solution. – Klaus D. Jul 24 '20 at 18:28
  • Unfortunately this did not work for me – APorter1031 Jul 24 '20 at 18:39
  • I was able to read the variable by exporting the variable in my cron command: `* * * * * export TESTING=1 && cd /opt/ && /usr/local/bin/python runner.py >> /var/log/cron.log 2>&1 `. This is not the desired solution though as I wish to keep the same cron job for both testing and production. – APorter1031 Jul 24 '20 at 18:49

1 Answers1

1

One possible solution is this to add in you Dockerfile something like this:

# install crontab
ENV TESTING=1

RUN echo "export TESTING=$TESTING" >> $HOME/.bashrc

And...

* * * * * . $HOME/.bashrc; cd /opt/ && /usr/local/bin/python runner.py >> /var/log/cron.log 2>&1

The dot before the $HOME is important.

  • 1
    Actually you can't use `source` (reliably and portably); `cron` uses `sh`, not `bash`; see also [Difference between sh and bash](https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash) – tripleee Jul 24 '20 at 19:29