アイレット株式会社 DX開発事業部 IoT×クラウドセクション コアエンジニアリンググループの井上です!
Laravel × Google Cloudでの開発において、
Cloud Runのジョブをgcloud run jobs execute
コマンドで実行する際、
複数引数の渡し方で少し手間取ったので解決方法をシェアいたします!
Laravelコマンドファイルの作成
- app/Console/Commands配下にRunTestJob.phpを作成
- 引数として
dataset
、table
、column_name
を受け取りたい
- 引数として
//app/Console/Commands/RunTestJob.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Jobs\TestJob; use Illuminate\Support\Facades\Log; class RunTestJob extends Command { protected $signature = 'run:test-job {dataset?} {table?} {column_name?}'; protected $description = 'Run the test job with the specified dataset, table, and column name'; public function handle() { $dataset = $this->argument('dataset') ?? null; $table = $this->argument('table') ?? null; $column_name = $this->argument('column_name') ?? null; // 実行ロジックをターミナルに出力 $this->info(sprintf("Running Test Job with Dataset: %s, Table: %s, and Column Name: %s.", $dataset, $table, $column_name)); // 必須チェックし、不足があればターミナルにエラーを出力し、終了 if (empty($dataset)) { $this->error('The "dataset" argument is required.'); return Command::INVALID; } if (empty($table)) { $this->error('The "table" argument is required.'); return Command::INVALID; } if (empty($column_name)) { $this->error('The "column_name" argument is required.'); return Command::INVALID; } // ジョブをディスパッチ前にログ出力 Log::debug(sprintf('Dispatching Test Job with Dataset: %s, Table: %s, and Column Name: %s', $dataset, $table, $column_name)); try { // ジョブをキューに追加 TestJob::dispatch($dataset, $table, $column_name); // ディスパッチ後に成功ログ Log::info(sprintf('Test Job dispatched successfully for Dataset: %s, Table: %s, and Column Name: %s', $dataset, $table, $column_name)); return Command::SUCCESS; } catch (\Exception $e) { // エラーログを出力 Log::error(sprintf('Error while dispatching Test Job. Error: %s', $e->getMessage())); $this->error($e->getMessage()); return Command::FAILURE; } } }
Cloud Runジョブ作成
- 今回はdatasetごとにジョブを分けて作成するという方針
- コンテナイメージのURL:画像はサンプル用のものだが実際はビルドしてpushしたものを設定
- ジョブ名:
test-dataset-test-job
dataset
は固定値のためジョブ側で設定:コンテナコマンドに設定table
、column_name
は呼び出し側(gcloud run jobs execute
コマンド側)で設定
- その他、接続タブ、セキュリティタブなどでの設定も必要だが本記事では割愛
gcloud run jobs executeコマンド作成
- argsに引数を設定
- 引数は
""
で囲う - 引数が複数の場合は等号または
,
を使用する公式ドキュメント参照
- 引数は
gcloud run jobs execute <JOB_NAME> \ --region <REGION> \ --args="<TABLE_NAME>,<COLUMN_NAME>"
ジョブ名:test-dataset-test-job
リージョン:asia-northeast1(東京)
テーブル:test_table
カラム:test_column
の場合の例↓↓↓
gcloud run jobs execute test-dataset-test-job \ --region asia-northeast1 \ --args="test_table,test_column"
(間違い例)
①引数それぞれをダブルクオーテーションで囲み半角スペースつなぎ--args="test_table" "test_column"
→コマンドエラーで怒られる
②引数それぞれをダブルクオーテーションで囲みカンマつなぎ--args="test_table","test_column"
→コマンドエラーで怒られる
③引数全体をダブルクオーテーションで囲み半角スペースつなぎ--args="test_table test_column"
→コマンドは通るがLaravel側で1つの引数として受け取ってしまいエラー
終わりに
gcloud run jobs execute
コマンドに引数を設定する方法を調べた際、
argsに設定する旨が書かれた記事はたくさんあったが、
引数が複数の場合の記事がなかったため、記事にしてみました!