Search code examples
google-cloud-platformgoogle-secret-managergoogle-cloud-pythongoogle-cloud-auth

Google Cloud SecretManagerServiceClient() is not finding creds with .from_service_account_json() file


Getting this error:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

Using the following python code:

from google.cloud import secretmanager

# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient().from_service_account_json("app/integrations/google/service_account.json")

The service account creds work correctly when using this from_service_account_json() in other Google services like tasks_client = tasks_v2.CloudTasksClient.from_service_account_json(settings.GOOGLE_CLOUD_KEY_FILE_NAME) and storage_client = storage.Client.from_service_account_json("app/keys/google-creds.json")

Why is it not working in this instance?


Solution

  • You need to use the function as a class rather than instance method:

    from google.cloud import secretmanager
    
    
    client = secretmanager.SecretManagerServiceClient.from_service_account_file(
        "/path/to/key.json",
    )
    

    Or you can create the credentials beforehand:

    from google.cloud import secretmanager
    from google.oauth2 import service_account
    
    credentials = service_account.Credentials.from_service_account_file(
        "/path/to/key.json",
    )
    
    client = secretmanager.SecretManagerServiceClient(
        credentials=credentials,
    )
    

    The method is valid but you'll generally be better placed using Application Default Credentials for portability and to keep config out of your code.