【问题标题】:environnement variables in system wide cron系统范围冠中的环境变量
【发布时间】:2019-12-15 05:09:23
【问题描述】:

我最近不得不从基于 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

异常表明,当脚本由 cron 运行时找不到 INFLUXDB_USER,但在手动运行时找到(或在 python shell 中询问 os.environ['INFLUXDB_USER'] 时)。

我尝试了什么

  • 采购命令(通过在其前面添加. /root/.bashrc;(也尝试过. /root/.profile;))
  • source /root/.bashrc 之后将其放入不同的shell 脚本
  • 使用绝对路径
  • 使用 bash 登录运行命令source
  • 将指令移动到cron.d
  • crontab-e添加命令而不是直接编辑/etc/crontab

由于/etc/environment 中没有定义 ENV 变量,我不确定这个“System Wide Cron”是否可以以任何方式访问它们。与我必须在 Alpine 中编辑的 /etc/crontab/root 相比,我发现这个 cron 非常令人困惑(它可以立即工作)。你如何处理这个“systemwide crontab”?这是 Debian 的特殊性吗?

编辑

  • 版本:cron/oldstable,now 3.0pl1-128+deb9u1 amd64
  • 使用 Docker 定义的环境变量存储在 /proc/1/environ 中(但采购它并没有改变任何事情)

【问题讨论】:

    标签: python shell docker cron debian


    【解决方案1】:

    我能找到的唯一直接的方法是通过稍微调整 Docker 映像的 entrypoint.sh 直接在 /etc/crontab 中写入变量。这是使用 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
    

    我对此不太满意,因此欢迎提供更优雅的解决方案。

    【讨论】:

      猜你喜欢
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2021-09-26
      • 2012-08-09
      相关资源
      最近更新 更多