Issue
I want a cron job and everything is already set up and cron is also working but unfortunately, cron is not getting my environment variables. I'm getting my environment variables using os
and they're working fine across the project but not in my cron.
settings.py
SECRET_KEY = os.environ.get('SECRET_KEY')
# Cron Jobs
CRONJOBS = [
('* * * * *', 'projects.cron.notifications_cron', '>> /cron/django_cron.log 2<&1')
]
crontab -e
* * * * /usr/local/bin/python /app/manage.py crontab run 744fbefdbf3ad30bec13
error in log file
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
when I set the SECRET_KEY
hardcoded in my settings.py
then it is working fine but I want to get it from my environment variables.
Solution
You can assign your environment variables into the crontab environment file (crontab -e
) so I convert all my environment variables into an env.txt
and merge the crontab environment file into that env.txt
file and replace the crontab environment file with my env.txt
.
crontab -e
default:
0 */24 * * * /usr/local/bin/python /app/manage.py crontab run 5d758d881d8f93b61f4d1b6a43eb72f6 >> /cron/django_cron.log 2<&1 # django-cronjobs for app
if you assign some VARIABLE in that file like below so the crontab will get that environment.
VARIABLE=value
0 */24 * * * /usr/local/bin/python /app/manage.py crontab run 5d758d881d8f93b61f4d1b6a43eb72f6 >> /cron/django_cron.log 2<&1 # django-cronjobs for app
here is the bash command to achieve it
$ printenv > env.txt # this will add all your environment variables in to env.txt
$ cat /var/spool/cron/crontabs/root >> env.txt # this will merge crontab environment file with your env.txt
$ cat env.txt > /var/spool/cron/crontabs/root # this will replace the crontab environment file with your env.txt
that's the only solution I produce on my own, hopefully, it will help you guys. thanks
Answered By - Zain Khan Answer Checked By - Marilyn (WPSolving Volunteer)