5.3. 使用 API 自动化 Red Hat Quay 进程


使用 API 时,有权访问 API 的 Red Hat Quay 管理员和用户可以自动执行重复性任务,如存储库管理或镜像修剪。

以下示例演示了如何使用 Python 脚本和 cron 作业来自动删除 OAuth 2 应用,但管理员的令牌 除外。如果要确保在一定时间段内循环与 OAuth 2 访问令牌关联的应用程序,这可能很有用。

先决条件

  • 您可以访问 Red Hat Quay API,它要求已创建了 OAuth 2 访问令牌。
  • 您已在 config.yaml 文件中设置了 BROWSER_API_CALLS_XHR_ONLY: false
  • 已使用以下内容安装了 Python 请求 库。
  • 您已在机器上启用了 cron 作业。
  • 您已创建了几个机构应用程序,包括不会被删除的应用程序。

流程

  1. 创建执行 API 命令的 Python 脚本。以下示例使用 DELETE /api/v1/organization/{orgname}/applications/{client_id} API 端点删除机构应用程序。

    example.py 文件

    import requests 1
    
    # Hard-coded values
    API_BASE_URL = "http://<quay-server.example.com>/api/v1" 2
    ACCESS_TOKEN = "<access_token>" 3
    ORG_NAME = "<organization_name>" 4
    
    def get_all_organization_applications():
        url = f"{API_BASE_URL}/organization/{ORG_NAME}/applications"
        headers = {
            "Authorization": f"Bearer {ACCESS_TOKEN}"
        }
    
        response = requests.get(url, headers=headers)
    
        if response.status_code == 200:
            try:
                applications = response.json()
                # Print the raw response for debugging
                print("Raw response:", applications)
    
                # Adjust parsing logic based on the response structure
                if isinstance(applications, dict) and 'applications' in applications:
                    applications = applications['applications']
    
                if isinstance(applications, list):
                    print("Organization applications retrieved successfully:")
                    for app in applications:
                        # Updated key from 'title' to 'name'
                        print(f"Name: {app['name']}, Client ID: {app['client_id']}")
                    return applications
                else:
                    print("Unexpected response format.")
                    return []
            except requests.exceptions.JSONDecodeError:
                print("Error decoding JSON response:", response.text)
                return []
        else:
            print(f"Failed to retrieve applications. Status code: {response.status_code}, Response: {response.text}")
            return []
    
    def delete_organization_application(client_id):
        url = f"{API_BASE_URL}/organization/{ORG_NAME}/applications/{client_id}"
        headers = {
            "Authorization": f"Bearer {ACCESS_TOKEN}"
        }
    
        response = requests.delete(url, headers=headers)
    
        if response.status_code == 204:
            print(f"Application {client_id} deleted successfully.")
        else:
            print(f"Failed to delete application {client_id}. Status code: {response.status_code}, Response: {response.text}")
    
    def main():
        applications = get_all_organization_applications()
        for app in applications:
            if app['name'] != "<admin_token_app>": <5>  # Skip the "admin-token-app"
                delete_organization_application(app['client_id'])
            else:
                print(f"Skipping deletion of application: {app['name']}")
    
    # Execute the main function
    main()

    1
    在 Python 代码中包括 导入 库。
    2
    附加了 /api/v1 的 registry 的 URL。
    3
    您的 OAuth 2 访问令牌。
    4
    保存应用程序的组织。
    要保留的应用程序令牌的名称。
  2. 将脚本保存为 prune_applications.py
  3. 创建自动运行脚本的 cron 作业:

    1. 运行以下命令打开 crontab 编辑器:

      $ crontab -e
    2. 在编辑器中,添加用于运行脚本的 cron 作业。以下示例按每月运行一次脚本:

      0 0 1 * * sudo python /path/to/prune_images.py >> /var/log/prune_images.log 2>&1
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.