请看说明再执行,出现删除过多概不负责。

网上找的版本删除有点问题,做了一定的修改。我这里的镜像都是依照数字正常排序构建的。例如v1.0.1

v1.0.1
v1.0.2
v1.0.3
v1.0.4
OLD_VERSION_NUM设置为3的话 会把v1.0.1删除。只保留后3个。

执行前先安装jq

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum install jq -y

shell(需放到harbor主机执行)

#!/bin/bash
set -e
HARBOR_URL=harbor.test.com
HARBOR_PASSWD=123456
#最大保留镜像个数。超过后的删除。
OLD_VERSION_NUM=20

function get_repos_list(){
  repos_list=$(curl -s -k -u admin:${HARBOR_PASSWD} https://${HARBOR_URL}/api/projects?page=1&page_size=50)
  mkdir -p $PWD/reposList
  echo "${repos_list}" | jq '.[]' | jq -r '.project_id' > $PWD/reposList/reposList.txt
}

function get_images_list(){
  mkdir -p $PWD/imagesList
  for repo in $(cat $PWD/reposList/reposList.txt);do
    images_list=$(curl -s -k -u admin:${HARBOR_PASSWD} https://${HARBOR_URL}/api/repositories?project_id=${repo})
    echo "${images_list}" | jq '.[]' | jq -r '.name' > $PWD/imagesList/${repo}.txt
  done
}

function delete_images(){
  htmlinfo=$(curl -s -k -u admin:${HARBOR_PASSWD} https://${HARBOR_URL}/api/repositories/$1/tags)
  tags=$(echo "${htmlinfo}" | jq ".[${index}]" | jq -r '.name')
  for tag in `echo ${tags} | awk 'BEGIN{i=1}{gsub(/ /,"\n");i++;print}' | sort -Vr | sed "1,${OLD_VERSION_NUM}d"`;do
    echo "images=$1 ************************** tag= ${tag}"
    curl -s -k -u admin:${HARBOR_PASSWD} -X DELETE https://${HARBOR_URL}/api/repositories/$1/tags/${tag}
  done

}

function clean_registry(){
  image_name=$(docker ps | grep registry | grep photon | awk -F " " '{print $2}')
  docker run --name gc --rm --volumes-from registry ${image_name} garbage-collect  /etc/registry/config.yml
}

function entrance(){
  get_repos_list
  get_images_list
  for repo in $(cat $PWD/reposList/reposList.txt);do
    for images in $(cat $PWD/imagesList/${repo}.txt); do
      delete_images ${images}
    done
  done
 clean_registry
}
entrance
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。