概要
Google Cloud Functions(Node.js)を実行したときに、GoogleAuthで「Could not load the default credentials.」と出た場合の対処方法
コード
こんな感じのコードで、
const { google } = require('googleapis');
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const authClient = await auth.getClient();
google.options({ auth: authClient });
こんな感じのエラーが出る場合、
Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/srv/node_modules/googleapis-common/node_modules/google-auth-library/build/src/auth/googleauth.js:155:19)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
環境変数を設定する方法もあるが、
鍵ファイル(JSON)のパスをGoogleAuthインスタンス生成時に直接指定する方法でも解消可能
(鍵ファイルは適切なロールが付与されたサービスアカウントで生成したもの)
const { google } = require('googleapis');
const auth = new google.auth.GoogleAuth({
keyFilename: './key.json',
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const authClient = await auth.getClient();
google.options({ auth: authClient });
※鍵ファイルは、functionsディレクトリ直下に置いてcloud functionsにデプロイ