5.3. API を使用した Red Hat Quay プロセスの自動化
API を使用すると、Red Hat Quay 管理者と API にアクセスできるユーザーは、リポジトリー管理やイメージのプルーニングなどの反復タスクを自動化できます。
次の例は、Python スクリプトと cron ジョブを使用して、管理者のトークン 以外 の OAuth 2 アプリケーションの削除を自動化する方法を示しています。これは、OAuth 2 アクセストークンに関連付けられたアプリケーションが一定期間後に確実に循環されるようにする場合に役立ちます。
前提条件
- Red Hat Quay API にアクセスできる。そのためには、OAuth 2 アクセストークンが作成済みでなければなりません。
-
config.yaml
ファイルでBROWSER_API_CALLS_XHR_ONLY: false
を設定している。 -
Python
requests
ライブラリーをインストールした。 - マシン上で 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 ジョブを追加します。次の例では、スクリプトを月に 1 回実行します。
0 0 1 * * sudo python /path/to/prune_images.py >> /var/log/prune_images.log 2>&1