LoginSignup
0
0

More than 1 year has passed since last update.

Cloud Tasks ClientでServiceAccountの鍵を使う

Last updated at Posted at 2022-01-28

1. サービスアカウントの鍵を用意する

※ 鍵を持っている場合、この手順はスキップしてください。

IAMと管理 > サービスアカウント
から既存のアカウントを選ぶか、新しく作成します

鍵を追加 > 新しい鍵を作成 > JSONをダウンロードします

スクリーンショット 2022-01-28 19.52.19.png

2. 必要な情報を抜き出す

以下のようなJSONがダウンロードできたと思います。

{
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

以下の情報を取り出します(コードで利用します)

  • projectId : project_id
  • clientEmail : client_email
  • privateKey : private_key

3. コードで利用

// サービスアカウントの情報を定義します
const projectId = serviceAccount.projectId;
const clientEmail = serviceAccount.clientEmail;
const privateKey = serviceAccount.privateKey;
const location = 'asia-northeast1'; // プロジェクトに合わせて変えてください

if (!projectId || !clientEmail || !privateKey)
  throw new Error('Missing service account credentials');
const client = new CloudTasksClient({
  projectId,
  credentials: {
    client_email: clientEmail,
    private_key: privateKey,
  },
});
const parent = client.locationPath(projectId, location);

CloudTasksClientのcredentialsにclientEmailとprivateKeyを含めるのがポイントです。

(環境変数GOOGLE_APPLICATION_CREDENTIALSにサービスアカウントキーのパスを指定でもいいです)

4. サービスアカウントに権限を付与

サービスアカウントに権限がないと以下のようなエラーが出ることがあります。

(node:1) UnhandledPromiseRejectionWarning: Error: 7 PERMISSION_DENIED: The principal (user or service account) lacks IAM permission "cloudtasks.queues.list" for the resource "projects/{ProjectID}/locations/asia-northeast1" (or the resource may not exist).

IAMと管理 > IAM
からサービスアカウントにCloud Tasks関連の権限を与えます

編集から
スクリーンショット 2022-01-28 20.11.36.png

「クラウドタスク管理者」を追加します(必要に応じて絞ってください)
スクリーンショット 2022-01-28 20.12.56.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0