DefaultCredentialsError
google.auth.exceptions.DefaultCredentialsError
Stack trace
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS environment variable or configure application default credentials.
Why it happens
The Google Vertex AI SDK requires authentication credentials to access the API. This error occurs when the SDK cannot find credentials in the environment variable GOOGLE_APPLICATION_CREDENTIALS or in the default application credentials path. Without valid credentials, the client cannot authenticate requests.
Detection
Check for DefaultCredentialsError exceptions when initializing the Vertex AI client or making API calls. Log or monitor for missing credentials errors to catch this before production failures.
Causes & fixes
GOOGLE_APPLICATION_CREDENTIALS environment variable is not set or points to a missing file
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the full path of your service account JSON key file before running your application.
Service account JSON key file is missing or inaccessible due to permissions
Ensure the service account key file exists at the specified path and the running user has read permissions.
Application default credentials are not configured on the machine or environment
Run 'gcloud auth application-default login' to configure default credentials or provide explicit credentials in code.
Code: broken vs fixed
from google.cloud import aiplatform
client = aiplatform.PipelineServiceClient()
# This line raises DefaultCredentialsError if credentials are missing
response = client.list_training_pipelines(parent="projects/my-project/locations/us-central1") import os
from google.cloud import aiplatform
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/your/service-account.json" # Set credentials path
client = aiplatform.PipelineServiceClient()
response = client.list_training_pipelines(parent="projects/my-project/locations/us-central1")
print(response) Workaround
Catch DefaultCredentialsError and prompt the user to set the environment variable or provide credentials explicitly in code to avoid crashes.
Prevention
Use environment management tools or container orchestration to ensure GOOGLE_APPLICATION_CREDENTIALS is always set correctly in all deployment environments.