我在Jenkins管道内使用AWS ECS CLI来自动化我的CICD。我想要做的是,如果服务还不存在,我想要创建一个基于任务定义的服务,如果服务已经存在,我只想更新它。下面是create-service cli命令:
aws ecs create-service \
--cluster $stg_cluster \
--task-definition $task_def \
--service-name $ecs_service \
--desired-count 1 \
--launch-type EC2 \
--scheduling-strategy REPLICA \
--load-balancers \"targetGroupArn=$target_group_arn,containerName=$container_name,containerPort=80\" \
--deployment-configuration \"maximumPercent=200,minimumHealthyPercent=100\" 它第一次运行良好,但在随后的部署中会因为此错误而失败:
调用CreateService操作时发生错误(InvalidParameterException):创建服务不是幂等的。
我认为我必须使用命令update-service,但不确定如何编写ECS命令来检查是否已经存在ECS服务。我可以想到的一种方法是,我可以从create-service cli命令中检查返回的代码,看看它是否等于0,但也不确定如何从管道中检索它。谢谢你的帮助。
发布于 2020-12-12 08:41:19
首先,您可以运行aws ecs describe-services来检查该服务是否已经存在,状态是否为ACTIVE。如果它是活动的,那么您可以运行aws ecs update-service来更新现有的服务。如果不是ACTIVE,那么可以运行aws ecs create-service来创建服务。
这是一个示例代码,可以用来检查服务是否已经创建并处于活动状态:
aws ecs describe-services --cluster CLUSTER_NAME --services SERVIVE_NAME | jq --raw-output 'select(.services[].status != null ) | .services[].status'然后使用if条件运行update-service或create-service。
发布于 2020-12-12 15:54:54
这是我的代码以防有人感兴趣。#Jenkinsfile管道
stage('Deploy')
{
steps {
....
script {
int count = sh(script: """
aws ecs describe-services --cluster $ecs_cluster --services $ecs_service | jq '.services | length'
""",
returnStdout: true).trim()
echo "service count: $count"
if (count > 0) {
//ECS service exists: update
echo "Updating ECS service $ecs_service..."
sh(script: """
aws ecs update-service \
--cluster $ecs_cluster \
--service $ecs_service \
--task-definition $task_def \
""")
}
else {
//ECS service does not exist: create new
echo "Creating new ECS service $ecs_service..."
sh(script: """
aws ecs create-service \
--cluster $ecs_cluster \
--task-definition $task_def \
--service-name $ecs_service \
--desired-count 1 \
--launch-type EC2 \
--scheduling-strategy REPLICA \
--load-balancers \"targetGroupArn=${target_group_arn},containerName=$app_name,containerPort=80\" \
--deployment-configuration \"maximumPercent=200,minimumHealthyPercent=100\"
""")
}
}
}
}发布于 2021-06-16 10:53:41
在aws cli中使用查询参数:
#!/bin/bash
CLUSTER="test-cluster-name"
SERVICE="test-service-name"
echo "check ECS service exists"
status=$(aws ecs describe-services --cluster ${CLUSTER} --services ${SERVICE} --query 'failures[0].reason' --output text)
if [[ "${status}" == "MISSING" ]]; then
echo "ecs service ${SERVICE} missing in ${CLUSTER}"
exit 1
fi在jenkins样条中也是如此:
stage('Deploy')
{
steps {
....
script {
string status = sh(script: """
aws ecs describe-services --cluster $ecs_cluster --services $ecs_service --query 'failures[0].reason' --output text
""",
returnStdout: true).trim()
echo "service status: $status"
if (status == 'MISSING') {
echo "ecs service: $ecs_service does not exists in $ecs_cluster"
// put create service logic
}
}}}https://stackoverflow.com/questions/65236242
复制相似问题