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_pathfunction get_repos_list(){mkdir -p $PWD/reposList>$PWD/reposList/reposList.txtfor i in `seq 1 8`;dorepos_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.txtdone
}
function get_images_list(){mkdir -p $PWD/imagesListrm -f $PWD/imagesList/*.txtfor repo in $(cat $PWD/reposList/reposList.txt);dofor j in `seq 1 20`;doimages_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}.txtdonedone
}
function conut_tags(){>images.txtfor k in `seq 1 100`;dohtmlinfo=$(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.txtdonesed -i 's/"//g' images.txt
}function change_images_txt(){>images1.txtnum=0for i in `cat $1`;dolet num++ #;echo $numif [ $((num%2)) -eq 1 ];thenIMG=$ielseCNT=$iecho "$IMG $CNT" >>images1.txtfidonecat images1.txt |sort |awk '{print $2,$1}' > images2.txt
}
function alert(){METRIC=$1LINE=`cat $METRIC|wc -l`if [ $LINE -gt 0 ];thenMSG=""while read line;doMSG="$MSG\n$line"done < $METRIC#echo -e $MSG#MSG=234567890CMD="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