python - 系统范围 cron 中的环境变量
问题描述
我最近不得不从基于 python Alpine的图像切换到所谓的python:3.7.2-slim(基于 Debian)。我的 cron 作业似乎不再起作用,因为cron 不再可以使用环境变量。我用这个测试脚本得出了这个结论:
# run.py
import os, sys
with open("/var/log/lastlog", "a") as f:
try:
user = os.environ['INFLUXDB_USER'] or "None"
f.write("I am running python as {} with {}\n".format(user, sys.version_info[:3]))
except Exception as e:
f.write("I failed: {}\n".format(str(e)))
还有这个 crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
# ADDED
*/1 * * * * root . /root/.bashrc; python3.7 /usr/src/collector/run.py
*/1 * * * * root echo 'hi' >> /var/log/lastlog
异常表明,INFLUXDB_USER
当脚本由 cron 运行时未找到,但在手动运行时(或os.environ['INFLUXDB_USER']
在 python shell 中询问时)找到。
我试过的
- 采购命令(通过
. /root/.bashrc;
在它前面添加(也尝试过. /root/.profile;
)) - 之后将其放入不同的 shell 脚本中
source /root/.bashrc
- 使用绝对路径
- 使用 bash 登录来运行命令源
- 将指令移动到
cron.d
- 添加命令
crontab-e
而不是/etc/crontab
直接编辑
由于 ENV VARIABLES 中没有定义/etc/environment
,我不确定这个“系统范围的 Cron ”是否可以以任何方式访问它们。/etc/crontab/root
与我必须在 Alpine 中编辑的(立即工作)相比,我发现这个 cron 相当令人困惑。你如何处理这个“系统范围的 crontab ”?这是 Debian 的特殊性吗?
编辑
- 版本:
cron/oldstable,now 3.0pl1-128+deb9u1 amd64
- 使用 Docker 定义的 env 变量存储在
/proc/1/environ
(但采购它并没有改变任何事情)
解决方案
/etc/crontab
我能找到的唯一直接方法是通过稍微调整entrypoint.sh
Docker Image来直接写入 VARIABLES 。这是一种在 sed 之后添加它们SHELL=/bin/sh
的方法
sed -i "/SHELL=\/bin\/sh/a INFLUXDB_USER=$INFLUXDB_USER" /etc/crontab
sed -i "/SHELL=\/bin\/sh/a PROJECT_NAME=$PROJECT_NAME" /etc/crontab
sed -i "/SHELL=\/bin\/sh/a INFLUXDB_USER_PASSWORD=$INFLUXDB_USER_PASSWORD" /etc/crontab
sed -i "/SHELL=\/bin\/sh/a INFLUXDB_DB=$INFLUXDB_DB" /etc/crontab
printf "3 */1 * * * root python /usr/src/collector/coin.py fetch cmc\n" >> /etc/crontab
printf "30 0 * * 4 root python /usr/src/collector/coin.py fetch gt --mode weekly\n" >> /etc/crontab
service cron restart
chmod 640 /etc/crontab
我对它不是很满意,所以欢迎任何更优雅的解决方案。
推荐阅读
- chef-infra - Chef [version-13.0.17] - 错误:无法将报告数据发布到服务器 (HTTP 400)
- java - Java Selenium ChromeDriver 程序在我的机器上运行很快,但在其他机器上运行缓慢
- regex - Python 正则表达式:Findall 组数最多
- javascript - 如何在 Node.js 中使用第二个构造函数的变量?(使用导入/导出)
- google-apps-script - 脚本 onForm 提交触发器无法正常工作
- python - 由于 Error=H10,Flask App 在通过 Heroku 部署时导致应用程序错误
- python - 编写一组 Dicom 图像
- json - 从嵌套的 json 中删除反斜杠
- wordpress - 如何在 Woocommerce 中以一种产品销售数字和实物商品?
- reactjs - 无法获取在我的 React 应用程序中工作的链接/路线