在AWS Elastic Beanstalk的Django中无需.ebextensions运行Cron的问题
在AWS Elastic Beanstalk的Django应用中配置Cron任务的问题
问题背景
我需要在AWS Elastic Beanstalk环境的Django应用中,通过Cron运行每日活跃用户统计函数。目前找到的相关教程都是多年前的版本,均要求使用.ebextensions文件夹中的.config文件。我的应用已正常运行一段时间,但不存在.ebextensions文件夹,因此怀疑配置或操作存在问题。
我的核心需求是:在AWS Elastic Beanstalk上的Django应用中运行Cron任务,优先希望通过代码配置并使用eb deploy部署,也接受在Linux实例上手动配置的方案。
尝试的解决方案与遇到的错误
方案1:自定义.ebextensions配置文件
我在项目根目录创建了.ebextensions文件夹,并在其中创建my_cron.config文件,内容如下:
files: /usr/local/bin/my_cron_script.sh: mode: "000755" owner: root group: root content: | #!/bin/bash export $(cat /opt/elasticbeanstalk/deployment/env | xargs) source $PYTHONPATH/activate python3 /var/app/current/manage.py dailyCounts /etc/cron.d/my_cron: mode: "000644" owner: root group: root content: | 0 6 00 * * root /usr/local/bin/my_cron_script.sh >> /var/log/my_cron.log 2>&1 commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true
执行eb deploy时出现以下错误:
2023-03-18 14:27:56 ERROR Updating Auto Scaling group named: awseb-e-XXXID-stack-AWSEBAutoScalingGroup-XXXID failed Reason: Unable to retrieve Endpoint.Address attribute for AWS::RDS::DBInstance, with error message DBInstance XXXID not found. (Service: Rds, Status Code: 404, Request ID: UUID-1234)
方案2:使用AWS官方示例配置
我直接尝试了AWS文档中的示例配置,内容如下:
packages: yum: jq: [] files: "/usr/local/bin/test_cron.sh": mode: "000755" owner: root group: root content: | #!/bin/bash INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id 2>/dev/null` REGION=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document 2>/dev/null | jq -r .region` # Find the Auto Scaling Group name from the Elastic Beanstalk environment ASG=`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" \ --region $REGION --output json | jq -r '.[][] | select(.Key=="aws:autoscaling:groupName") | .Value'` # Find the first instance in the Auto Scaling Group FIRST=`aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names $ASG \ --region $REGION --output json | \ jq -r '.AutoScalingGroups[].Instances[] | select(.LifecycleState=="InService") | .InstanceId' | sort | head -1` # If the instance ids are the same exit 0 [ "$FIRST" = "$INSTANCE_ID" ] "/usr/local/bin/cron_example.sh": mode: "000755" owner: root group: root content: | #!/bin/bash /usr/local/bin/test_cron.sh || exit # Now run commands that should run on only 1 instance. echo "Cron running at "`date` > /tmp/cron_example.log "/etc/cron.d/cron_example": mode: "000644" owner: root group: root content: | * * * * * root /usr/local/bin/cron_example.sh commands: rm_old_cron: command: "rm -fr /etc/cron.d/cron_example.bak" ignoreErrors: true
但部署时抛出了一个“null”错误,网上找不到相关解决方案。
核心疑问
- 我是否存在明显的操作错误?
- 是否有类似
django-cron的更好替代方案?
内容的提问来源于stack exchange,提问作者BookofMorten
相关产品推荐
相关产品推荐

