如何通过curl输出使Azure Pipelines任务在镜像不存在时失败?
在Azure DevOps YAML管道中实现镜像未找到时SSH任务失败的方案
方案1:利用curl的-f参数基于HTTP状态码判断
当镜像不存在时,镜像仓库通常会返回4xx(如404)的HTTP状态码,默认curl会忽略这类状态码返回0,添加-f参数后,curl会在HTTP状态码≥400时返回非0退出码,触发Azure DevOps任务失败。
修改后的curl命令:
curl -sS -f -X GET "https://registry/api/v2.0/Projects/test/repositories/repository%2Ftest-module/artifacts/1.0.0/tags?page=1&page_size=10&with_signature=false&with_immutable_status=false" -H "accept: application/json"
-f(--fail):让curl在HTTP状态码为4xx/5xx时返回非0退出码-sS:静默模式但保留错误输出,比单独的-s更便于排查问题
方案2:基于返回的JSON内容判断(适用于返回200但无数据的场景)
如果镜像不存在时仓库仍返回200状态码,但返回的JSON为空数组或total_count为0,可以用以下方式解析内容并判断:
方法A:使用jq解析JSON(推荐)
假设返回的JSON结构包含total_count字段表示结果数量:
curl -s -X GET "https://registry/api/v2.0/Projects/test/repositories/repository%2Ftest-module/artifacts/1.0.0/tags?page=1&page_size=10&with_signature=false&with_immutable_status=false" -H "accept: application/json" | jq 'if .total_count == 0 then exit 1 else . end'
如果返回的是纯数组(如[]),则判断数组长度:
curl -s -X GET "https://registry/api/v2.0/Projects/test/repositories/repository%2Ftest-module/artifacts/1.0.0/tags?page=1&page_size=10&with_signature=false&with_immutable_status=false" -H "accept: application/json" | jq 'if length == 0 then exit 1 else . end'
注意:如果目标服务器未安装jq,需要先通过
apt-get install jq(Debian/Ubuntu)或yum install jq(CentOS/RHEL)安装。
方法B:使用grep简单匹配关键字
如果返回内容中存在artifactid表示镜像存在,反之则不存在:
response=$(curl -s -X GET "https://registry/api/v2.0/Projects/test/repositories/repository%2Ftest-module/artifacts/1.0.0/tags?page=1&page_size=10&with_signature=false&with_immutable_status=false" -H "accept: application/json") echo "$response" if ! echo "$response" | grep -q "artifactid"; then exit 1 fi
关键说明
Azure DevOps的SSH任务默认会检测命令的退出码,只要命令返回非0值,任务就会自动标记为失败,无需额外配置。
内容的提问来源于stack exchange,提问作者Julie
相关产品推荐
相关产品推荐

