Automatically clean up the harbor mirror warehouse script

Automatically clean up the harbor mirror warehouse script

Please read the instructions before proceeding, and will not be responsible for excessive deletions.

There was a problem with the deletion of the version found on the Internet, and certain modifications were made.
The mirror images here are all constructed according to the normal order of numbers. E.g

v:1.0.1
v:1.0.2
v:1.0.3
v:1.0.4
OLD_VERSION_NUM设置为3的话 会把v:1.0.1删除。只保留后3个。

Jq must be installed before execution

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

shell(Must be placed on the harbor host for execution

#!/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}' | awk -F. '{print $NF}' | sort -nr | sed "1,${OLD_VERSION_NUM}d"`;do
    echo "images=$1 ************************** tag= v1.0.${tag}"
    curl -s -k -u admin:${HARBOR_PASSWD} -X DELETE https://${HARBOR_URL}/api/repositories/$1/tags/v1.0.${tag}
  done

}

function clean_registry(){
    
    
  image_name=$(docker ps | grep registry | grep photon | awk -F " " '{print $2}')
  docker run -it --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

Guess you like

Origin blog.csdn.net/lswzw/article/details/108120748