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 作业。
- 您已创建了几个机构应用程序,包括不会被删除的应用程序。
流程
创建执行 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()
-
将脚本保存为
prune_applications.py
。 创建自动运行脚本的 cron 作业:
运行以下命令打开 crontab 编辑器:
$ crontab -e
在编辑器中,添加用于运行脚本的 cron 作业。以下示例按每月运行一次脚本:
0 0 1 * * sudo python /path/to/prune_images.py >> /var/log/prune_images.log 2>&1