ElasticBeanstalk 用于处理同时仅在 1 个实例中运行的脚本

问题描述 投票:0回答:2
#!/bin/sh

SQS_QUEUE_URL="url"
AWS_REGION="eu-central-1"
LOCK_KEY="supervisor-lock"
# Unique identifier for the lock

# Attempt to acquire the lock by sending a message to the queue
lock_acquired=$(aws sqs send-message --queue-url "$SQS_QUEUE_URL" --region "$AWS_REGION" --message-body "$LOCK_KEY")
echo "Lock Acquired: $lock_acquired"

sleep 5

message=$(aws sqs receive-message --queue-url "$SQS_QUEUE_URL" --region "$AWS_REGION" --max-number-of-messages 1 --wait-time-seconds 0 --query "Messages[0].ReceiptHandle")

echo $message

if [ -n "$message" ]; then

    if [ "$ENVIRONMENT_NAME" = "development" ]; then
        echo "Starting Supervisor setup..."
        # handle in case you here it fails
        sudo mkdir -p /var/log/supervisor
        sudo mkdir -p /var/log/celery
        cp -r /var/app/current/supervisor /etc
        export $(cat /opt/elasticbeanstalk/deployment/env | xargs)
        source /var/app/venv/*/bin/activate
        #/var/app/venv/staging-LQM1lest/bin/supervisorctl -c /etc/supervisor/project-supervisord.conf shutdown
        #sleep 5
        /var/app/venv/staging-LQM1lest/bin/supervisord -c /etc/supervisor/project-supervisord.conf
        echo "Starting Supervisor..."

        # Release the lock by deleting the message from the queue
        aws sqs delete-message --queue-url "$SQS_QUEUE_URL" --receipt-handle "$message" --region eu-central-1

        echo "message deleted"
    elif [ "$ENVIRONMENT_NAME" = "production" ]; then
        # Start supervisor only in development environment
        echo "Skipping Supervisor setup in production environment."
    fi

else
    echo "Failed to acquire the lock. Another instance is already setting up Supervisor."
fi

所以我有一个始终并行运行 2 个实例的 EB 环境。当我部署时,我希望命令仅在一个实例中运行。 因此,我们的想法是拥有一个消息锁定机制,以便这两个实例以某种方式有一种通信方式。 我还希望由于自动扩展的启动,它能够适应 ec2 的替换。 因此,如果运行主管的实例被替换,它应该再次运行主管。始终且一次仅出现 1 次。

我从这个脚本 atm 得到的结果是命令在两个实例中运行,并且我在队列中留下了 2 条消息。

我想要得到的是队列中的 0 条消息和在 1 个实例中运行的主管。

我确实手动运行了这些命令,它们都有效,删除也有效,但似乎没有删除消息,我也收到了打印消息。

有人可以帮忙吗

amazon-web-services amazon-elastic-beanstalk devops
2个回答
0
投票

您必须使用 容器命令 运行脚本,并将

leader_only
标志设置为
true
。这样它只会在一个实例上执行。


0
投票

好的,我在部署后使用 eb hooks 有没有办法用它来做到这一点,或者更好地将脚本移动到容器命令?

   00_deploy_hook_permissions:
     command: |
       sudo find .platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \;
       sudo find /var/app/staging/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \;
© www.soinside.com 2019 - 2024. All rights reserved.