5.4. Automating Red Hat Quay processes by using the API


With the API, Red Hat Quay administrators and users with access to the API can automate repetitive tasks such as repository management or image pruning.

The following example shows you how you might use a Python script and a cron job to automate the deletion of OAuth 2 applications except the administrator’s token. This might be useful if you want to ensure an application associated with an OAuth 2 access token is cycled after a certain period of time.

Prerequisites

  • You have access to the Red Hat Quay API, which entails having already created an OAuth 2 access token.
  • You have installed the Python requests library using.
  • You have enabled cron jobs on your machine.
  • You have created several organization applications, including one that will not be deleted.

Procedure

  1. Create a Python script that executes an API command. The following example is used to delete organization applications using the DELETE /api/v1/organization/{orgname}/applications/{client_id} API endpoint.

    example.py file

    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
    Includes the import library in your Python code.
    2
    The URL of your registry appended with /api/v1.
    3
    Your OAuth 2 access token.
    4
    The organization that holds the application.
    The name of the application token to remain.
  2. Save the script as prune_applications.py.
  3. Create a cron job that automatically runs the script:

    1. Open the crontab editor by running the following command:

      $ crontab -e
    2. In the editor, add the cron job for running the script. The following example runs the script once per month:

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

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 문서 정보

Legal Notice

Theme

© 2026 Red Hat
맨 위로 이동