Python脚本调用harbor api retentions新建项目并创建保留规则和定时执行

本文介绍了如何使用Python脚本操作Harbor平台,包括创建项目和为新项目添加保留策略,仅保留最近推送的3个镜像,并设置每天0点执行。
摘要由CSDN通过智能技术生成

1. Python脚本

import argparse
import requests

def create_project(harbor_url, username, password, project_name):
    # 构建请求头
    headers = {
        "Content-Type": "application/json"
    }

    # 构建认证信息
    auth = (username, password)

    # 查询项目列表
    response = requests.get(f"{harbor_url}/api/v2.0/projects", auth=auth)
    projects = response.json()

    # 检查项目是否存在
    project_exists = any(project["name"] == project_name for project in projects)

    # 如果项目不存在,则创建项目
    if not project_exists:
        data = {
            "project_name": project_name,
        }
        response = requests.post(f"{harbor_url}/api/v2.0/projects", json=data, auth=auth, headers=headers)
        if response.status_code == 201:
            print(f"项目 {project_name} 创建成功")
        else:
            print(f"项目 {project_name} 创建失败:{response.text}")
    else:
        print(f"项目 {project_name} 已经存在")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create project in Harbor")
    parser.add_argument("--harbor_url", type=str, help="Harbor host URL")
    parser.add_argument("--username", type=str, help="Username for authentication")
    parser.add_argument("--password", type=str, help="Password for authentication")
    parser.add_argument("--project_name", type=str, help="Name of the project to create")

    args = parser.parse_args()

    create_project(args.harbor_url, args.username, args.password, args.project_name)

2. 用法

python3 create_harbor_project.py --harbor_url=改为自己harbor地址 --username=admin --password=Harbor12345 --project_name=test111

脚本新增功能

调用harbor 的 retentions接口,执行添加保留策略
说明:
在新建项目的基础上,增加策略中的保留规则和定时执行
保留规则:只保留最新推送的3个镜像
定时执行:定时每天0点执行

用法与上面一致
import argparse
import requests

def create_project(harbor_url, username, password, project_name):
    # 构建请求头
    headers = {
        "Content-Type": "application/json"
    }

    # 构建认证信息
    auth = (username, password)

    # 查询项目列表
    response = requests.get(f"{harbor_url}/api/v2.0/projects", auth=auth)
    projects = response.json()
    # 检查项目是否存在
    project_exists = any(project["name"] == project_name for project in projects)

    # 如果项目不存在,则创建项目
    if not project_exists:
        data = {
            "project_name": project_name,
        }
        response = requests.post(f"{harbor_url}/api/v2.0/projects", json=data, auth=auth, headers=headers)
        if response.status_code == 201:
            print(f"Harbor项目 {project_name} 创建成功")
            # 创建成功后,再次查询项目列表,获取到新建项目的ID
            response = requests.get(f"{harbor_url}/api/v2.0/projects", auth=auth)
            projects = response.json()
            for i in projects:
                if i['name'] == project_name:
                    print(f"{project_name}项目ID为:{i['project_id']}")
                    # 给此项目新建保留镜像策略:只保留最近推送的3个镜像,并设定每天0点执行
                    policy_data = {
                        "algorithm": "or",
                        "rules": [
                            {
                                "action": "retain",
                                "params": {"latestPushedK": 3},
                                "scope_selectors": {
                                    "repository": [
                                        {"decoration": "repoMatches", "kind": "doublestar", "pattern": "**"}
                                    ]
                                },
                                "tag_selectors": [
                                    {"decoration": "matches", "extras": "{\"untagged\":true}", "kind": "doublestar", "pattern": "**"}
                                ],
                                "template": "latestPushedK"
                            }
                        ],
                        "scope": {"level": "project", "ref": i['project_id']},
                        "trigger": {
                            "kind": "Schedule",
                            "settings": {"cron": "0 0 0 * * *"}  # 每天执行
                        }
                    }
                    response = requests.post(f"{harbor_url}/api/v2.0/retentions", json=policy_data, auth=auth, headers=headers)
                    if response.status_code == 201:
                        print(f"{project_name}项目保留策略添加成功:每天执行一次,保留最近推送的3个镜像")
                    else:
                        print(f"{project_name}项目保留策略添加出错:{response.text}")

        else:
            print(f"Harbor项目 {project_name} 创建失败:{response.text}")
    else:
        print(f"Harbor项目 {project_name} 已经存在")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create project in Harbor")
    parser.add_argument("--harbor_url", type=str, help="Harbor host URL")
    parser.add_argument("--username", type=str, help="Username for authentication")
    parser.add_argument("--password", type=str, help="Password for authentication")
    parser.add_argument("--project_name", type=str, help="Name of the project to create")

    args = parser.parse_args()

    create_project(args.harbor_url, args.username, args.password, args.project_name)
要使用Golang调用Harbor API删除镜像,可以按照以下步骤进行操作: 1. 导入相关的Golang软件包: ```go import ( "bytes" "net/http" ) ``` 2. 构建HTTP请求: ```go func createRequest(method, url string, payload []byte) (*http.Request, error) { req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") return req, nil } ``` 3. 发送HTTP请求并获取响应: ```go func sendRequest(req *http.Request) (*http.Response, error) { client := http.DefaultClient resp, err := client.Do(req) if err != nil { return nil, err } return resp, nil } ``` 4. 构建删除镜像的URL: ```go func buildDeleteURL(baseURL, projectName, repoName, tag string) string { return fmt.Sprintf("%s/api/repositories/%s/%s/tags/%s", baseURL, projectName, repoName, tag) } ``` 5. 执行删除镜像的操作: ```go func deleteImage(baseURL, projectName, repoName, tag, username, password string) error { url := buildDeleteURL(baseURL, projectName, repoName, tag) req, err := createRequest("DELETE", url, nil) if err != nil { return err } req.SetBasicAuth(username, password) resp, err := sendRequest(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("Failed to delete image. Status code: %d", resp.StatusCode) } return nil } ``` 其中,baseURL是Harbor的URL,projectName是项目名称,repoName是镜像仓库名称,tag是镜像标签,username和password是Harbor API的登录凭证。 通过以上步骤,就可以使用Golang调用Harbor API删除镜像了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值