🐳

Node.js から Cloud Run Job 叩く

2024/08/20に公開

意外と引数付きで叩く時の方法が転がってなかったので備忘録。

  • gcloud auth application-default loginした後環境変数にGOOGLE_APPLICATION_CREDENTIALS のパスをセットしておく
  • npm install @google-cloud/run しておく

https://cloud.google.com/nodejs/docs/reference/run/latest/overview

import { JobsClient } from '@google-cloud/run';

const projectId = process.env.GC_PROJECT_ID;
const location = process.env.GC_REGION;
const jobName = process.env.JOB_NAME; // Cloud Run Job の名前

const fullJobName = `projects/${projectId}/locations/${location}/jobs/${jobName}`;

export async function executeCloudRunJob(id: number) {
  const runClient = new JobsClient();

  async function callRunJob() {
    const request = {
      name: fullJobName,
      overrides: {
        containerOverrides: [
          {
            env: [
              {
                name: 'ID',
                value: id.toString(),
              },
            ],
          },
        ],
      },
    };

    const [operation] = await runClient.runJob(request);
    console.log('Operation started:', operation.name);

    // Jobのキックだけできれば良いという場合はここを消す
    const [response] = await operation.promise();
    console.log(response);
  }

  try {
    await callRunJob();
  } catch (error) {
    console.error('Error executing Cloud Run Job:', error);
    throw error;
  }
}

Discussion