standalone_migrations gemを使ったLambda関数を使ったマイグレーション実装

先日よりLambda関数にてデータベースのマイグレーションを実装することを実装しています。これまではTypeScriptで実装したのですが、個人的な趣味で今回はRubyで実装したいと思います。

Rubyの場合、standalone_migrations gemを使うのが一番早いかなと思います。

github.com

RailsのDB Migrationとおなじ使い勝手でRailsなしで使えるgemです。

Gemfileを以下のように記し、bundle installします。

# frozen_string_literal: true

source "https://rubygems.org"

gem 'standalone_migrations'
gem 'pg'

Rakefileは以下のように実装します。

require 'standalone_migrations'
StandaloneMigrations::Tasks.load_tasks

今回は検証目的としてマイグレーションを行うファイルをdb/migrate以下に作ります。

class CreateArticles < ActiveRecord::Migration[8.1]
  def change
    create_table :articles do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

接続先設定はdb/config.ymlとして作成しておきます。

development:
  adapter: postgresql
  encoding: unicode
  database: <%= ENV['DB_NAME'] %>
  host: <%= ENV['DB_HOST'] %>
  username: <%= ENV['DB_USER'] %>
  password: <%= ENV['DB_PASSWORD'] %>

production:
  adapter: postgresql
  encoding: unicode
  database: <%= ENV['DB_NAME'] %>
  host: <%= ENV['DB_HOST'] %>
  username: <%= ENV['DB_USER'] %>
  password: <%= ENV['DB_PASSWORD'] %>

test: &test
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

Lambda関数自身はコンテナイメージで動かしたいので以下のようなDockerfileを作成します。

# --- Stage 1: Build Stage ---
FROM public.ecr.aws/lambda/ruby:3.4 AS builder

# ビルドに必要な依存関係をインストール
RUN dnf -y install postgresql15-devel gcc make libyaml-devel

COPY Gemfile Gemfile.lock ${LAMBDA_TASK_ROOT}/

# 本番用gemのみをインストールし、キャッシュを削除
RUN bundle config set --local deployment 'true' && \
    bundle config set --local without 'development test' && \
    bundle install && \
    rm -rf vendor/bundle/ruby/3.4.0/cache/*.gem && \
    find vendor/bundle/ruby/3.4.0/gems/ -name "*.c" -delete && \
    find vendor/bundle/ruby/3.4.0/gems/ -name "*.o" -delete

# --- Stage 2: Final Stage ---
FROM public.ecr.aws/lambda/ruby:3.4

# 実行時に最低限必要な共有ライブラリのみをインストール(develやgccは入れない)
RUN dnf -y install libpq libyaml && \
    dnf clean all

# ビルドステージからインストール済みのgemをコピー
COPY --from=builder ${LAMBDA_TASK_ROOT}/vendor/bundle ${LAMBDA_TASK_ROOT}/vendor/bundle
COPY --from=builder ${LAMBDA_TASK_ROOT}/.bundle ${LAMBDA_TASK_ROOT}/.bundle

# アプリケーションコードをコピー
COPY . ${LAMBDA_TASK_ROOT}

CMD [ "lambda_function.lambda_handler" ]

Lambda関数自身は以下のとおり。Rakefileを読み込み、タスクを呼び出します。

require 'rake'
require 'standalone_migrations'

# Rakeタスクのロード(一度だけ行う)
load 'Rakefile'

def lambda_handler(event:, context:)
  begin
    # db:migrateタスクを実行
    # reenableしないと、Lambdaコンテナが再利用された際に2回目以降動かない場合があります
    Rake::Task['db:migrate'].reenable
    Rake::Task['db:migrate'].invoke

    { statusCode: 200, body: "Migration successful!" }
  rescue => e
    { statusCode: 500, body: "Migration failed: #{e.message}" }
  end
end

あとはLambda関数を動かします。ただ、デフォルト設定ではschema.rbが書き込みできないところに出力されます。

ただ、マイグレーション自身はうまくできています。

$ psql -h xxxxxxxxxxxxxxxxxxxxxxxxxxxx --dbname db1 --username postgres
Password for user postgres:
psql (17.7, server 17.6)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql)
Type "help" for help.

db1=> \dt
                List of relations
 Schema |         Name         | Type  |  Owner
--------+----------------------+-------+----------
 public | ar_internal_metadata | table | postgres
 public | articles             | table | postgres
 public | schema_migrations    | table | postgres
(3 rows)

db1=> select * from articles;
 id | body | created_at | title | updated_at
----+------+------------+-------+------------
(0 rows)

db1=> select * from schema_migrations;
    version
----------------
 20260125055959
(1 row)

db1=> select * from ar_internal_metadata;
     key     |                  value                   |         created_at         |         updated_at
-------------+------------------------------------------+----------------------------+----------------------------
 environment | development                              | 2026-01-28 05:50:49.697901 | 2026-01-28 05:50:49.697905
 schema_sha1 | bc585952c5648a89177904fdd53921f56caa3875 | 2026-01-28 05:50:49.73613  | 2026-01-28 05:50:49.736135
(2 rows)

db1=>

schema.rbが書き込みできないことやそもそもマイグレーションファイルの格納先をカスタマイズするには、ルートディレクトリに.standalone_migrationsを作成し、以下のような設定を記述します。

db:
  seeds: /path/to/db/seeds.rb
  migrate: /path/to/db/migrate
  schema: /path/to/db/schema.rb
config:
  database: db/config.yml

LambdaはEFSをマウントできるので、EFS上にマイグレーションファイルなどを格納するのが良いかと思います。

docs.aws.amazon.com

なお、TypeScriptで発生したSSLについては今回の実装では特別設定しなくてもSSLで接続できました。