harbor api v2.0
- v2.0
v2.0
“harbor api v2.0”与原来区别较大,此处harbor也做了https。另外,通过接口拿到的数据也是只能默认1页10个,所以脚本根据实际情况一页页的抓取数据
脚本主要用于统计repo、image,以及所有镜像的tag数,change_images_txt用于调整格式,函数alert将tag数大于30的告警出来,最后登录harbor,将告警的镜像中较老的tag手动清理掉(当然也可以通过如下接口拿到所有镜像的tag,根据时间来排序,将较老的部分通过接口自动删除,但是“reference”这个参数获取比较复杂,暂未采用这种方式)
#!/bin/bash
HARBOR_URL=harbor.example.com
HARBOR_USER=admin
HARBOR_PASSWD=Harbor12345
#OLD_VERSION_NUM=30
script_path=$(dirname $0)
cd $script_path
function get_repos_list(){
mkdir -p $PWD/reposList
>$PWD/reposList/reposList.txt
for i in `seq 1 8`;do
repos_list=$(curl -s -k -u ${HARBOR_USER}:${HARBOR_PASSWD} https://${HARBOR_URL}/api/v2.0/projects?page=$i)
echo "${repos_list}" | jq '.[]' | jq -r '.name' >> $PWD/reposList/reposList.txt
done
}
function get_images_list(){
mkdir -p $PWD/imagesList
rm -f $PWD/imagesList/*.txt
for repo in $(cat $PWD/reposList/reposList.txt);do
for j in `seq 1 20`;do
images_list=$(curl -s -k -u ${HARBOR_USER}:${HARBOR_PASSWD} https://${HARBOR_URL}/api/v2.0/projects/$repo/repositories?page=$j)
echo "${images_list}" | jq '.[]' | jq -r '.name' >> $PWD/imagesList/${repo}.txt
done
done
}
function conut_tags(){
>images.txt
for k in `seq 1 100`;do
htmlinfo=$(curl -s -k -u ${HARBOR_USER}:${HARBOR_PASSWD} https://${HARBOR_URL}/api/v2.0/repositories?page=$k)
echo $htmlinfo |jq '.[]|select(.artifact_count > 30)'|jq '.name, .artifact_count' >> images.txt
done
sed -i 's/"//g' images.txt
}
function change_images_txt(){
>images1.txt
num=0
for i in `cat $1`;do
let num++ #;echo $num
if [ $((num%2)) -eq 1 ];then
IMG=$i
else
CNT=$i
echo "$IMG $CNT" >>images1.txt
fi
done
cat images1.txt |sort |awk '{print $2,$1}' > images2.txt
}
function alert(){
METRIC=$1
LINE=`cat $METRIC|wc -l`
if [ $LINE -gt 0 ];then
MSG=""
while read line;do
MSG="$MSG\n$line"
done < $METRIC
#echo -e $MSG
#MSG=234567890
CMD="curl -H \"Content-Type:application/json\" -X POST --data '{\"mobile\":\"13123456789\",\"message\":\"新镜像仓库镜像tag数>30$MSG\",\"priority\":\"2\",\"moserial\":\"1234567\"}' http://xxxxxxxxxxxxxxxx"
#echo "$CMD"
eval "$CMD"
fi
}
conut_tags
change_images_txt images.txt
alert images2.txt