3
0

GitHub Actionsを活用して自動デプロイを導入する方法

Last updated at Posted at 2024-03-24

概要

この記事では、GitHub Actionsを使用してRailsアプリケーションをAWS EC2インスタンスに自動デプロイする方法を解説します。このプロセスには、秘密鍵の生成、GitHubに秘密鍵を保存、Capistranoでのデプロイ設定が含まれます。

環境

*Ruby 3.2.0
*Rails 7.0.8
*Capostrano 3.18.0
*EC2

※前提として、Capistranoの実行に必要なGemや設定などは導入済みであるものとします。通常はローカル上でbundle exec cap production deploy コマンドを実行するものとします。また、CapstranoはSSH接続ができることを前提としています。

参考リソース

公開鍵・秘密鍵の作成

SSHキーを生成して、サーバーとGitHubの間で安全な通信を確立します。

ssh-keygen -t rsa -b 4096 -f ~/.ssh/[鍵の名称]

公開鍵のコピー

生成された公開鍵をクリップボードにコピーします。M

cat ~/.ssh/[鍵の名称].pub | pbcopy

サーバー上に公開鍵を登録

次に、サーバーの~/.ssh/authorized_keysファイルに公開鍵を追加します。

vim ~/.ssh/authorized_keys

GitHub Actionsでの環境変数の登録

GitHubのリポジトリにアクセスし、Settings > secrets and variables > Actionsで作成した秘密鍵(SSH_KEY)とサーバーの情報(KNOWN_HOSTS)を環境変数として登録します。

Image from Gyazo

Image from Gyazo

rails_cd.ymlの作成

GitHub Actionsの設定ファイルrails_cd.ymlを作成し、以下の内容を追加します。

.github/workflows/rails.cd.yml

name: Rails CD

on:
  push:
    branches:
      - main
jobs:
  deploy:
    name: Capistrano Deploy
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Install SSH key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_KEY }}
          name: github-actions # optional
          known_hosts: ${{ secrets.KNOWN_HOSTS }}
          if_key_exists: fail # replace / ignore / fail; optional (defaults to fail)

      - uses: actions/checkout@v3
      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          bundler-cache: true

      - name: Deploy to EC2
        run: |
          eval "$(ssh-agent -s)"
          ssh-add ~/.ssh/github-actions
          BRANCH=main bundle exec cap production deploy

deploy.rbの修正

Capistrano設定ファイルdeploy.rbを以下のように修正します。

config/deploy.rbの修正
# capistranoのバージョンを記載。固定のバージョンを利用し続け、バージョン変更によるトラブルを防止する
lock '3.18.0'

# Capistranoのログの表示に利用する
set :application, 'cleanrestroom'

# どのリポジトリからアプリをpullするかを指定する
set :repo_url,  'git@github.com:sirokuma-2/cleanrestroom.git'
set :branch, 'main'

# バージョンが変わっても共通で参照するディレクトリを指定
set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system', 'public/uploads')

set :rbenv_type, :user
set :rbenv_ruby, '3.2.0'

# どの公開鍵を利用してデプロイするか
set :ssh_options, auth_methods: ['publickey'],
                  keys: [File.expand_path('~/.ssh/[鍵の名称]')] #ここを修正

# プロセス番号を記載したファイルの場所
set :unicorn_pid, -> { "#{shared_path}/tmp/pids/unicorn.pid" }

# Unicornの設定ファイルの場所
set :unicorn_config_path, -> { "#{current_path}/config/unicorn.rb" }
set :keep_releases, 5

# デプロイ処理が終わった後、Unicornを再起動するための記述
after 'deploy:publishing', 'deploy:restart'
namespace :deploy do
  task :restart do
    invoke 'unicorn:restart'
  end
end

実行結果

githubのmainブランチにマージすると自動デプロイが開始します。
Image from Gyazo

結論

この記事では、RailsアプリケーションをAWS EC2に自動デプロイするための設定方法を解説しました。具体的には、秘密鍵の生成、GitHub Secretsによる秘密鍵の管理、GitHub Actionsを使用した自動デプロイフローの設定、Capistranoを使用したデプロイ設定の例を提供しました。

これらのステップに従って設定を完了することで、開発者はコードの変更を主要ブランチにプッシュするだけで、自動的にサーバーへのデプロイが行われるようになります。これにより、デプロイプロセスを効率化し、より速く安全にアプリケーションのリリースを行うことができるようになります。

3
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
3
0