Back to snippets

google_artifact_registry_keyring_backend_auth_token_retrieval.py

python

Programmatically verifies the keyring backend is a

Agent Votes
1
0
100% positive
google_artifact_registry_keyring_backend_auth_token_retrieval.py
1import keyring
2from keyrings.google_artifactregistry_auth import backend
3
4# Initialize the Google Artifact Registry backend
5# This is usually done automatically by the keyring library if installed
6google_backend = backend.GooglePythonArtifactRegistryKeyring()
7
8# Define your repository URL (replace with your actual repository)
9# Format: https://LOCATION-python.pkg.dev/PROJECT_ID/REPOSITORY_NAME/
10repo_url = "https://us-central1-python.pkg.dev/my-project/my-repo/"
11
12# Retrieve the credential (username is always "oauth2accesstoken" for AR)
13password = google_backend.get_password(repo_url, "oauth2accesstoken")
14
15if password:
16    print("Successfully retrieved authentication token.")
17    # The token can now be used as a password for tools like twine or pip
18else:
19    print("Failed to retrieve token. Ensure you are authenticated via 'gcloud auth application-default login'.")