【エラー】google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application

エラー

$ docker-compose up <SEVICE_NAME>
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

解決方法

$ gcloud auth application-default login

Credentials saved to file: [/Users/saneatsuwakana/.config/gcloud/application_default_credentials.json]

後は、作成されたjsonファイルをGOOGLE_APPLICATION_CREDENTIALSに指定して読み込ませればOK。

dockerの場合は以下のように「docker-compose.yml」に記述する。

app_name:
    environment:
      - GOOGLE_APPLICATION_CREDENTIALS=application_default_credentials.json

その他

以下のエラーが出た場合...

ERROR - 403 POST https://translation.googleapis.com/language/translate/v2/detect: Your application has authenticated using end user credentials from the Google Cloud SDK or Google Cloud Shell which are not supported by the translate.googleapis.com. We recommend that most server applications use service accounts instead. For more information about service accounts and how to use them in your application, see https://cloud.google.com/docs/authentication/.

公式サイトを参考に以下のコマンドでjsonファイルを作成する

$ gcloud iam service-accounts create <NAME>
$ gcloud projects add-iam-policy-binding <PROJECT_ID> --member "serviceAccount:<NAME>@<PROJECT_ID>.iam.gserviceaccount.com" --role "roles/owner"
$ gcloud iam service-accounts keys create <FILENAME>.json --iam-account <NAME>@<PROJECT_ID>.iam.gserviceaccount.com

Getting Started with Authentication  |  Authentication  |  Google Cloud