79616008

Date: 2025-05-10 23:10:48
Score: 0.5
Natty:
Report link

After trying to deploy locallly first and via cloud run, I have fixed the issue. It is just need to refresh the ADC credentials, due to the validity status false (expired).
Here is the code :

def _get_credentials():
    """
    Mendapatkan kredensial menggunakan Application Default Credentials (ADC).
    Di lingkungan Cloud Run, ini akan menggunakan service account yang terkait.
    """
    try:
        logging.info("Attempting to get credentials using google.auth.default()...")
        credentials, project_id = google.auth.default(scopes=SCOPES)
        logging.info(f"Successfully obtained ADC. Project ID: {project_id}, Type: {type(credentials)}")

        if hasattr(credentials, 'service_account_email'):
             logging.info(f"ADC: Service Account Email (from ADC): {credentials.service_account_email}")
        else:
             logging.info("ADC: Service Account Email attribute not found (expected for user creds from gcloud auth application-default login, not typical for SA on Cloud Run).")

        # Periksa validitas awal ADC
        adc_initially_valid = credentials and credentials.valid
        logging.info(f"ADC: Credentials initial valid check: {adc_initially_valid}")

        # Jika kredensial ADC awalnya tidak valid, coba lakukan refresh.
        # Ini akan memastikan upaya refresh selalu dilakukan jika ADC tidak langsung valid.
        if not adc_initially_valid and credentials:
            logging.warning("ADC: Credentials initially invalid. Attempting refresh...")
            try:
                credentials.refresh(Request())
                logging.info("ADC: Credentials refresh attempt completed.") # Log setelah refresh dicoba
            except Exception as adc_refresh_err:
                logging.error(f"ADC: Failed during credentials refresh attempt: {adc_refresh_err}", exc_info=True)
                # Biarkan credentials.valid akan diperiksa di bawah
        
        if not credentials.valid:
            # Ini seharusnya tidak terjadi di Cloud Run dengan SA yang dikonfigurasi dengan benar.
            logging.warning("Credentials obtained but are not marked as valid after potential refresh. This might indicate an issue with the ADC setup or permissions.")
            # Anda bisa memutuskan untuk mengembalikan None di sini jika validitas sangat krusial
            # return None

        return credentials
    except google.auth.exceptions.DefaultCredentialsError as e:
        logging.error(f"Failed to get Application Default Credentials: {e}", exc_info=True)
        return None
    except Exception as e:
        logging.error(f"An unexpected error occurred while getting credentials: {e}", exc_info=True)
        return None

@app.route('/check-adc')
def perform_adc_check():
    """Melakukan tes untuk mendapatkan ADC."""
    logging.info("Performing ADC check...")
    credentials = _get_credentials()
    if credentials and credentials.valid:
        logging.info("ADC check successful: Credentials obtained and are valid.")
        project_id_msg = f"Project ID from ADC: {credentials.project_id}" if hasattr(credentials, 'project_id') else "Project ID not directly available on credentials object."
        return f"ADC Check OK: Credentials obtained and are valid. {project_id_msg}", 200
    elif credentials and not credentials.valid:
        logging.error("ADC check found credentials, but they are NOT valid.")
        return "ADC Check FAILED: Credentials obtained but are not valid.", 500
    else:
        logging.error("ADC check FAILED: Could not obtain credentials.")
        return "ADC Check FAILED: Could not obtain credentials.", 500

Thanks

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Irsyam Asri Putra