Last active
December 11, 2025 10:42
-
-
Save masterPiece93/ddb50f984b0db32a3f192a169b66f7ca to your computer and use it in GitHub Desktop.
GCP ADC Check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| GCP ADC ( Application Default Credentials ) Authentication Check Module | |
| This module handles the checking responsibility | |
| of weather ADC is setup for the project or not . | |
| Test: | |
| python3 -m gcp_authenticate | |
| """ | |
| import os | |
| import google.auth | |
| from google.auth.exceptions import DefaultCredentialsError | |
| from typing import Optional, Callable | |
| def check_gcp_adc_status(logger: Optional[Callable]=None, log_console: bool=False): | |
| """Checks if Application Default Credentials are available and valid. | |
| args: | |
| logger (Optional[Callable]) : a callback that does the logging according to you . | |
| log_console (bool) : if print on stdot/console needed . | |
| """ | |
| try: | |
| # Attempt to find the default credentials | |
| credentials, project = google.auth.default() | |
| _msg1 = f"""ADC found. | |
| Project ID: {project} | |
| """ | |
| def do_logging(msg: str, level: str = 'info'): | |
| if logger: | |
| logger(msg, level=level) | |
| if log_console: | |
| print(msg) | |
| do_logging(_msg1) | |
| # Optional: You can check details about the credentials found | |
| if hasattr(credentials, "service_account_email"): | |
| _msg2=f"ADC Credential type: Service Account ({credentials.service_account_email})" | |
| do_logging(_msg2) | |
| elif hasattr(credentials, "quota_project"): | |
| _msg2=f"ADC Credential type: User Account (Quota Project: {credentials.quota_project})" | |
| do_logging(_msg2) | |
| else: | |
| _msg2="ADC Credential type: Unknown/Other" | |
| do_logging(_msg2) | |
| return True | |
| except DefaultCredentialsError as e: | |
| _msg3="ADC is not configured" | |
| do_logging(_msg3) | |
| return False | |
| except Exception as e: | |
| do_logging(f"An unexpected error occurred while checking ADC: {e}", 'debug') | |
| return False | |
| if __name__ == '__main__': | |
| # Run the check | |
| if check_gcp_adc_status() or 'GOOGLE_APPLICATION_CREDENTIALS' in os.environ: | |
| # You can now confidently use other GCP client libraries | |
| print("\nProceeding with GCP client library operations.") | |
| else: | |
| print("\nPlease run `gcloud auth application-default login` or set the GOOGLE_APPLICATION_CREDENTIALS environment variable.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # entrypoint of your project | |
| """ | |
| This is the sample of using in your project. | |
| - If ADC is not set , fallback to service account . | |
| """ | |
| import os | |
| PATH_TO_SERVICE_ACCOUNT_FILE = 'mounted/location/of/service/account/file/in/your/machine/file.json' | |
| if check_gcp_adc_status(logger = lambda msg, **kwargs: log.info(msg)) or 'GOOGLE_APPLICATION_CREDENTIALS' in os.environ: | |
| # You can now confidently use other GCP client libraries | |
| log.info("GCP Autentication Found . Proceed with GCP client library operations.") | |
| elif os.path.exists(PATH_TO_SERVICE_ACCOUNT_FILE): | |
| os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = str(PATH_TO_SERVICE_ACCOUNT_FILE) | |
| log.info("GCP Service Account File Set . Proceed with GCP client library operations.") | |
| else: | |
| raise Exception("Please run `gcloud auth application-default login` or set the GOOGLE_APPLICATION_CREDENTIALS environment variable.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment