Open4

Larave on Kamal2におけるPusher用シークレットの設定方法

uruositeuruosite

https://zenn.dev/uruosite/scraps/c1fe514770e42b

上記のScrapに従い、serversideup/php:8.4-fpm-nginx-alpine でLaravelイメージをデプロイしたい。

Laravel Pusherを使おうとすると、下記のようなエラーになった。

※そもそもWebSocketサーバーを立てれば済む話だが、まだReverbサーバーを立てるのは試せてない状況

secretsは正常なので戸惑った。

#26 3.379    TypeError
#26 3.379
#26 3.379   Pusher\Pusher::__construct(): Argument #1 ($auth_key) must be of type string, null given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastManager.php on line 306
#26 3.379
#26 3.379   at vendor/pusher/pusher-php-server/src/Pusher.php:63
#26 3.383      59▕      * @param ClientInterface|null $client [optional] - a Guzzle client to use for all HTTP requests
#26 3.383      60▕      *
#26 3.383      61▕      * @throws PusherException Throws exception if any required dependencies are missing
#26 3.383      62▕      */
#26 3.383   ➜  63▕     public function __construct(string $auth_key, string $secret, string $app_id, array $options = [], ClientInterface $client = null)
#26 3.383      64▕     {
#26 3.383      65▕         $this->check_compatibility();
#26 3.383      66▕
#26 3.383      67▕         $useTLS = true;
#26 3.383
#26 3.383       +7 vendor frames

背景

LaravelのBroadcastingドライバとしてPusherを選択すると、PusherのPHP SDKの初期化が呼ばれる。
その際、下記のようにkey, secret, idが要求される。
デプロイ環境に物理的な.envがあるなら、黙示的に展開されているため問題ない。
ただ、KamalのようにDockerコンテナをビルドする環境では、3つの変数をビルド時に伝える必要が生じる。

https://github.com/pusher/pusher-http-php/blob/master/src/Pusher.php#L44-L64

uruositeuruosite

ステップ1. deploy.ymlのbuilder secretsを追加

下記のようにbuilderのsecretsを追加する。

https://kamal-deploy.org/docs/configuration/builders/#build-secrets

非常に紛らわしいが、env->secretとは別のセクションである。

config/deploy.yml
builder:
  arch: amd64
  cache:
    type: gha
  secrets:
  # 重要: 下記がないとpusher/pusher-php-server/src/Pusher.phpでエラーになる
    - PUSHER_APP_KEY
    - PUSHER_APP_SECRET
    - PUSHER_APP_ID
uruositeuruosite

ステップ2: Dockerfile内で呼び出す

# スクリプトとoptimize-autoloaderつきで改めてインストール
# 重要: 下記がないとpusher/pusher-php-server/src/Pusher.phpでエラーになる
# uid=82 はwww-dataのUID
# https://serversideup.net/open-source/docker-php/docs/guide/understanding-file-permissions#how-it-works
RUN --mount=type=secret,id=PUSHER_APP_KEY,uid=82 \
    --mount=type=secret,id=PUSHER_APP_SECRET,uid=82 \
    --mount=type=secret,id=PUSHER_APP_ID,uid=82 \
    PUSHER_APP_KEY=$(cat /run/secrets/PUSHER_APP_KEY) \
    PUSHER_APP_SECRET=$(cat /run/secrets/PUSHER_APP_SECRET) \
    PUSHER_APP_ID=$(cat /run/secrets/PUSHER_APP_ID) \
    composer install --no-interaction --prefer-dist --optimize-autoloader

https://serversideup.net/open-source/docker-php/docs/guide/understanding-file-permissions#how-it-works

今回はAlpineなので、www-dataのUIDが82になっている点に注意

uruositeuruosite

以上でcomposer install時のエラーは回避。

まだまだLaravel on kamal2の実例が少ないため、Pusherの本番運用は様子見中。

(Laravel CloudといったIaaSのロックインを回避するために、VPSにデプロイする手段は確保しておきたい。)