1
2

RailsのActive StorageでCloud Storageを設定をする

Last updated at Posted at 2024-02-17

概要

Rails7でActive Storageを使用して、Google CloudのCloud Storageの設定の仕方の記事です。設定するときに、このような記事がありそうでなかったので書きます。

前提

Active Storageの設定が終わって、保存先が以下のlocalの設定では動くものとします。

development.rb or production.rb
  config.active_storage.service = :local

Active Storageの設定が終わっていな人はこちらを参考に設定してください。

Google Cloudの設定

Cloud Storageの設定

  1. Cloud Storageを開いてバケットの作成
  2. ロケーションタイプ、リージョンを設定(単一リージョンが1番安い)
  3. デフォルトのクラスやアクセス制御を設定
  4. 公開アクセスを禁止で問題ない

サービスアカウントの作成

  1. APIとサービスを開いて、メニューから認証情報を開く
  2. 認証情報を作成からサービスアカウントを選択
  3. サービス名を入力して、ロールをCloud Storageのオブジェクト管理者に設定して完了
  4. 作成したサービスアカウントを選択、メニューからキーを選択、鍵を追加、新しい鍵を作成、キーのタイプをJSONで作成し保存

Railsの設定

  1. 以下をGemfileに追加
    gem "google-cloud-storage"
    
  2. google-cloud-storageをインストール
    bundle install
    
  3. config/storage.ymlに以下を記述する。{プロジェクト名}、{バケット名}に先ほど設定したものを記入
    google:
      service: GCS
      project: {プロジェクト名}
      credentials:
        {
          "type": "service_account",
          "project_id": "<%= Rails.application.credentials.dig(:google_cloud_storage, :project_id) %>",
          "private_key_id": "<%= Rails.application.credentials.dig(:google_cloud_storage, :private_key_id) %>",
          "private_key": "<%= Rails.application.credentials.dig(:google_cloud_storage, :private_key) %>",
          "client_email": "<%= Rails.application.credentials.dig(:google_cloud_storage, :client_email) %>",
          "client_id": "<%= Rails.application.credentials.dig(:google_cloud_storage, :client_id) %>",
          "auth_uri": "<%= Rails.application.credentials.dig(:google_cloud_storage, :auth_uri) %>",
          "token_uri": "<%= Rails.application.credentials.dig(:google_cloud_storage, :token_uri) %>",
          "auth_provider_x509_cert_url": "<%= Rails.application.credentials.dig(:google_cloud_storage, :auth_provider_x509_cert_url) %>",
          "client_x509_cert_url": "<%= Rails.application.credentials.dig(:google_cloud_storage, :client_x509_cert_url) %>",
          "universe_domain": "googleapis.com"
        }
      bucket: {バケット名}
    
  4. Credentialsにキーを書く
    vimで開いて
    EDITOR="vim" bin/rails credentials:edit
    
    先ほど作成したJSONのキーを参考に以下を記入して保存
    jsonファイルから"と,を削除すればコピペするだけ
    google_cloud_storage:
        type: service_account
        project_id: xxxx
        private_key_id: xxxx
        client_email: xxxx
        private_key: xxxx
        client_id: xxxx
        auth_uri: xxxx
        token_uri: xxxx
        auth_provider_x509_cert_url: xxxx
        client_x509_cert_url: xxxx
    
  5. development.rbまたはproduction.rbで保存先をgoogle cloud storageに設定
    config.active_storage.service = :google
    

これで設定完了

1
2
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
1
2