目 录CONTENT

文章目录

自动清理docker registry镜像的Python脚本及使用方法

Seven
2023-05-02 / 0 评论 / 0 点赞 / 592 阅读 / 4363 字 / 正在检测是否收录...

下面是一个自动清理docker registry镜像的Python脚本:

import requests
import json
import datetime
# 镜像仓库地址
registry_url = "http://your.registry.com"
# 镜像仓库用户名
registry_username = "your_username"
# 镜像仓库密码
registry_password = "your_password"
# 清理镜像的时间间隔(天)
clean_time = 7
# 登录镜像仓库
def registry_login():
    login_url = registry_url + "/v2/users/login"
    payload = {
        "username": registry_username,
        "password": registry_password
    }
    headers = {
        "Content-Type": "application/json"
    }
    r = requests.post(login_url, data=json.dumps(payload), headers=headers)
    token = r.json()["token"]
    return token
# 获取所有镜像的tags
def get_image_tags():
    token = registry_login()
    headers = {
        "Authorization": "Bearer " + token
    }
    tags_url = registry_url + "/v2/_catalog"
    r = requests.get(tags_url, headers=headers)
    images = r.json()["repositories"]
    tags = {}
    for image in images:
        tags_url = registry_url + "/v2/" + image + "/tags/list"
        r = requests.get(tags_url, headers=headers)
        image_tags = r.json()["tags"]
        tags[image] = image_tags
    return tags
# 获取镜像的创建时间
def get_image_created_time(image, tag):
    token = registry_login()
    headers = {
        "Authorization": "Bearer " + token,
        "Accept": "application/vnd.docker.distribution.manifest.v2+json"
    }
    manifest_url = registry_url + "/v2/" + image + "/manifests/" + tag
    r = requests.get(manifest_url, headers=headers)
    created_time_str = r.headers["Docker-Content-Digest"].split(":")[1]
    created_time_int = int(created_time_str, 16)
    created_time = datetime.datetime.utcfromtimestamp(created_time_int)
    return created_time
# 删除镜像
def delete_image(image, tag):
    token = registry_login()
    headers = {
        "Authorization": "Bearer " + token
    }
    delete_url = registry_url + "/v2/" + image + "/manifests/" + tag
    r = requests.delete(delete_url, headers=headers)
    return r.status_code
# 自动清理镜像
def clean_images():
    tags = get_image_tags()
    for image in tags.keys():
        for tag in tags[image]:
            created_time = get_image_created_time(image, tag)
            current_time = datetime.datetime.utcnow()
            diff_time = (current_time - created_time).days
            if diff_time >= clean_time:
                status_code = delete_image(image, tag)
                if status_code == 202:
                    print("Delete image %s:%s successful." % (image, tag))
                else:
                    print("Delete image %s:%s failed, status code: %d." % (image, tag, status_code))
if __name__ == '__main__':
    clean_images()

使用方法:

1.将代码保存为clean_registry_images.py文件;
2.修改registry_urlregistry_usernameregistry_password变量为你的镜像仓库地址、用户名和密码;
3.修改clean_time变量为需要清理的镜像的最小存活时间(天);
4.在命令行中运行python clean_registry_images.py命令即可自动清理镜像。

0

评论区