在弹性豆茎上每天运行一个简单的cron作业的最新方法是什么?



我知道这个问题以前有人问过,但是在过去的十年里答案已经改变了很多次,并且有很多方法可以解决这个问题的不太具体的版本。

我有一个python应用程序部署在Elastic Beanstalk (python 3.8运行在64位Amazon Linux 2/3.4.1上)。

我需要每天至少提取一次数据,并且我有一个提取数据的函数。我可以在python或shell脚本中调用它。

我如何设置这个?

您必须在. ebeextensions中添加如下文件:

cron.config

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/my_cron.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.
cd /var/app/current
sudo -u ec2-user your_funtion
"/etc/cron.d/my_cron":
mode: "000644"
owner: root
group: root
content: |
15 7 * * * root /usr/local/bin/my_cron.sh
commands:
rm_old_cron:
command: "rm -fr /etc/cron.d/my_cron.bak"
ignoreErrors: true

在以上代码中:

sudo -u ec2-user your_funtion

您应该在这里输入要运行的函数的路径,并且:

15 7 * * * root /usr/local/bin/my_cron.sh

在我的示例中,cron任务每天早上7点15分执行,因此您应该使用Linux cron命令语法设置时间。

test_cron.sh例程用于查明是否有多个EC2实例在运行,在这种情况下,避免在多个实例中执行cron作业。(这部分摘自AWS文档)。

要执行test_cron.sh例程,EC2实例应该具有权限集,这可以通过向IAM中的laws -elasticbeanstalk- EC2 -role角色添加以下策略来完成(您还可以在环境启动期间由EB创建此角色):

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1409855610000",
"Effect": "Allow",
"Action": [ "autoscaling:DescribeAutoScalingGroups" ],
"Resource": [ "*" ]
},
{
"Sid": "Stmt1409855649000",
"Effect": "Allow",
"Action": [ "ec2:DescribeTags" ],
"Resource": [ "*" ]
}
]
}

最新更新