获取harbor某个项目下所有镜像及 ID

需求:把harbor某个仓库组下的所有镜像名字及镜像ID收集出来;
镜像仓库为使用Docker-compose快速部署。
注意:所收集到的镜像有多个tag的话,脚本是根据tag的创建时间,取最新的tag。

于是编写如下脚本:

#!/bin/bash
#
read -p "Please enter the password of harbor: " -s PASSWD
# Note: please modify the harbor address, user name
# eg:HARBOR= http://hubIP
HARBOR=
USER=
#

# Convert to requirement format
AUTH=$(echo $USER:$PASSWD| base64)
#
# Get project
# PROJECT=$(curl -H"Authorization: Basic $AUTH" $HARBOR/api/projects? | awk '/"name": /'|awk -F "\"" '{print $4}')

curl -H"Authorization: Basic $AUTH" $HARBOR/api/projects?
if [ $? -ne 0 ];then
   echo "Please enter the correct user name and password"
   exit 100
fi
#
# Get all image, no tag, only name
IMAGE_RANG=$(curl -H"Authorization: Basic $AUTH"  $HARBOR/api/search?q=system_containers | grep "repository_name" |awk -F "\"" '{print $4}')

# Make sure the file that stores the image is new
workdir=$(cd $(dirname $0); pwd)
if [ -f $workdir/a.tst ];then
    mv $workdir/a.tst $(date +%Y%m%d%H%M%S).a.tst.bak
fi

# Get the latest tag and ID for all images
for i in ${IMAGE_RANG};do
    #
    # Get the creation time of the latest image
    NEW_TAG_TIME=$(curl -H"Authorization: Basic $AUTH" $HARBOR/api/repositories/$i/tags|awk '/"created"/'|sort -k 2| tail -n 1|awk -F '"' '{print $4}')

    # Get the latest tag of the image
    NEW_TAG=$(curl -H"Authorization: Basic $AUTH" $HARBOR/api/repositories/$i/tags |grep -B 7 "${NEW_TAG_TIME}" |awk '/"name": /' | awk -F '"' '{print $4}')

    # Because there may be multiple tags for the same image, you need to use the for loop
    for h in ${NEW_TAG};do
        #Image, Image name and tag
        IMAGE=$(echo $i:$h)
        # Get image ID, 
        IMAGE_ID=$(curl -H"Authorization: Basic $AUTH" $HARBOR/api/repositories/$i/tags/$h/manifest | grep -A 7 manifest | grep digest | awk -F : '{print $3}')
        # Intercepts the first 12 bits of the image ID
        IMAGE_ID_NEW=$(echo ${IMAGE_ID:0:12})
        # Merge the image name and ID into one line
        ID_IMAGE=$(echo $IMAGE  $IMAGE_ID_NEW)

        # Load the image name into a new file
        echo ${ID_IMAGE} >>a.tst
     done
done

#
# Format file content
IMAGE_FILE=`date +%Y%m%d%H%M%S.harbor_image.txt`
awk '{printf "%-60s %70s\n",$1,$2}' $workdir/a.tst >${IMAGE_FILE}

if [ $? -eq 0 ];then
    rm -rf  $workdir/a.tst
fi

echo "Please check the ${IMAGE_FILE} file."

使用说明:
1、在使用脚本时需注意修改脚本内的一些需求参数
获取harbor某个项目下所有镜像及 ID
2、全局搜索system_containers ,替换为想要获取的项目名称;
获取harbor某个项目下所有镜像及 ID
3、修改完成后,保存退出,并进行执行,执行完成后,会在当前目录生成一个以当前时间命名的文件,查看文件,如下图所示:
获取harbor某个项目下所有镜像及 ID
至此镜像名及镜像ID获取完成。

猜你喜欢

转载自blog.51cto.com/14086194/2688102

相关文章