我正在设置一个 docker 容器,它需要一个 cronjob 来使用awscli.
我的 cron 作业无法访问 docker 容器的环境变量时遇到问题。当我在启动时工作时,我将所有环境变量打印到一个文件中printenv > /env。
当我尝试source从 cron 作业中使用时(我直接在 crontab 和 crontab 调用的脚本中都尝试过),它似乎不起作用。
我制作了我的项目的简化版本来演示这个问题(包括rsyslog日志记录):
Dockerfile:
FROM debian:jessie
# Install aws and cron
RUN apt-get -yqq update
RUN apt-get install -yqq awscli cron rsyslog
# Create cron job
ADD crontab /etc/cron.d/hello-cron
RUN chmod 0644 /etc/cron.d/hello-cron
# Output environment variables to file
# Then start cron and watch log
CMD printenv > /env && cron && service rsyslog start && tail -F /var/log/*
Run Code Online (Sandbox Code Playgroud)
定时任务:
# Every 3 minutes try to source /env and run `aws s3 ls`.
*/3 * * * * root /usr/bin/env bash & source /env & aws s3 ls >> /test 2>&1
Run Code Online (Sandbox Code Playgroud)
当我启动容器时,我可以看到/env是用我的变量创建的,但它永远不会被获取。
首先,命令的(好吧,shell 内置的)名称是source. 除非您编写了一个名为 的脚本source并将其放入,否则/您想要source而不是/source。
下一个问题是,cron通常使用您拥有的任何东西,/bin/sh并且source是 bashism(或其他此类更复杂的外壳)。用于获取文件的可移植的、符合 POSIX 标准的命令是.. 所以,试试这个,而不是source:
*/3 * * * * root /usr/bin/env bash & . /env & aws s3 ls >> /test 2>&1
Run Code Online (Sandbox Code Playgroud)
另外,我不太明白那应该做什么。启动 bash 会话并将其发送到后台有什么意义?如果要使用 bash 运行后续命令,则需要:
*/3 * * * * root /usr/bin/env bash -c '. /env && aws s3 ls' >> /test 2>&1
Run Code Online (Sandbox Code Playgroud)
我还更改了&,&&因为就我所见,在后台采购毫无意义。