0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【トラブルシューティング】Cloud Run×suno-apiで環境変数が渡らない問題を解決した話

Last updated at Posted at 2025-03-06

背景

suno-api をCloud Run上でビルド・デプロイしたところ、一部のAPIが500エラーを返す事象に遭遇。

調べてみると、環境変数で渡している SUNO_COOKIE がうまく渡っていないことが原因らしい。でも、Cloud Run側の環境変数としては設定済み
「あれ?おかしいぞ?」ってなったので、Dockerfileをチェックしてみたら、発見しました。

ARG SUNO_COOKIE

こいつかーーー!!!(犯人確定)
Cloud Runの環境変数はランタイムでしか見えないので、ビルド時には見えてないのが原因でした。

ゴール

  • SUNO_COOKIE安全にDocker Build時に渡す
  • Gitに載せない
  • なるべくGCP標準機能(Cloud Buildのsubstitutions)で解決する

そもそもCloud Buildで環境変数を渡すには?

方法 説明 Gitに秘密は載る?
① cloudbuild.yamlのsubstitutions ビルド時にGUIから変数注入 乗らない✨
② Dockerfileに直書き Dockerfileに直接ベタ書き 乗る💀

迷わず①を採用。Cloud BuildのGUIから「代入変数(substitutions)」を定義して、毎回注入する形に。

cloudbuild.yaml での設定例

以下のように--build-argを仕込んで、GUI側のsubstitutionsと連携します。

cloudbuild.yaml

steps:
  - name: gcr.io/cloud-builders/docker
    args:
      - build
      - '--no-cache'
      - '-t'
      - >-
        $_AR_HOSTNAME/$_AR_PROJECT_ID/$_AR_REPOSITORY/$REPO_NAME/$_SERVICE_NAME:$COMMIT_SHA
      - '-f'
      - Dockerfile
      - '--build-arg'
      - 'SUNO_COOKIE=$_SUNO_COOKIE' # ここで代入変数を取得
      - .
    id: Build

substitutions

substitutions:
  _AR_PROJECT_ID: xxxxx
  _TRIGGER_ID: xxxxx
  _PLATFORM: managed
  _SERVICE_NAME: xxxxx
  _DEPLOY_REGION: xxxx
  _AR_HOSTNAME: xxxx
  _AR_REPOSITORY: xxxxx
  _SUNO_COOKIE: 'dummy' # GUI上から取得した代入変数が毎回セットされる。

実際のビルドログ

Before(渡せてない)

 ---> 6bbde929d339
Step 12/19 : RUN if [ -z "$SUNO_COOKIE" ]; then echo "Warning: SUNO_COOKIE is not set. You will have to set the cookies in the Cookie header of your requests."; fi
 ---> Running in e14c5e9401c6
Warning: SUNO_COOKIE is not set. You will have to set the cookies in the Cookie header of your requests.
Removing intermediate container e14c5e9401c6

After(substitutionsで渡せた)

 ---> 529fb246c51c
Step 12/19 : RUN if [ -z "$SUNO_COOKIE" ]; then echo "Warning: SUNO_COOKIE is not set. You will have to set the cookies in the Cookie header of your requests."; fi
 ---> Running in 5019523db1b0
Removing intermediate container 5019523db1b0

学びポイント

  • Cloud Runの環境変数はランタイムの話。ビルド時には渡らない。
  • Cloud Buildのsubstitutionsを活用すれば、Gitに秘密を載せずに安全に渡せる。
  • cloudbuild.yamlは、GCPのCloud Buildでデフォルト生成されるので、それをちょっと編集すればOK。
  • DockerfileでARG受けして、ENVに流し込むのもポイント。

まとめ

本家のIssueでも議論されてたけど、なかなかスッキリした答えがなかったので、ビルド時とデプロイ後の環境変数の違いを理解して一発解決できたのは大きな学びでした。

Cloud Build&Cloud Runの連携で環境変数ハマったら、まずは「ビルド時のsubstitutions」をチェック!これだけでだいぶ事故防げるのでオススメです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?