LoginSignup
1
0

More than 1 year has passed since last update.

【CI/CD】RailsアプリケーションにCI/CDを構築

Last updated at Posted at 2022-09-23

0. 前提

  • Dockerで構築したRailsアプリケーションをHerokuでデプロイしていること

手動デプロイを毎回行うのが面倒なので、CI/CDを導入しデプロイを自動化する

CIとは

  • 継続的インテグレーション(Continuous Integration)
    • ソースコードを変更してGitHubにアップする度にビルドやテストを自動実行し、コードの品質を一定に保つ方法

CDとは

  • 継続的デリバリー(Continuous Delivery)
    • テストを通った変更→レビューOK→マージされたらデプロイを自動的に行う仕組み

CircleCIとは

  • CI/CDを構築するためのサービス
    • ビルド・テスト・デプロイをCloud上で行ってくれる

1. コードをGitHubにアップする

  • Git
    • コードはGitでバージョンを管理
      • 元に戻せる
      • 変更履歴が分かる
  • GitHub
    • Gitで管理しているソースコードをオンライン上で共有するためのサービス

GitHub上でリポジトリ作成

  • GitHubのYour Repositoriesにアクセス→newボタン押下
  • Ownerを選択し、Repository nameにはここまでで作ってきたHerokuのアプリケーション名を入力
  • Publicを選択し、Create Repositoryボタン押下

Gitでコードを管理

$ cd ~/Documents/rails_docker/ # アプリケーションディレクトリに移動
$ git init # Gitの管理下(リポジトリ)におくコマンド

リポジトリ・・・ディレクトリやファイルの状態を記録する場所


.gitignoreファイルを修正

  • .gitignore・・・バージョン管理する必要の無いファイルをGitのバージョン管理下から外すことができる
    • データベースの接続先情報など、GitHubにアップすると情報漏洩の危険性があるもの
    • bundle installでダウンロードしてくるファイルのコードも変更履歴を管理する必要がない
    • .gitignoreファイルに管理不要なファイルを指定しておくことで、そのファイルをバージョン管理から外すことができる
    • .gitignoreファイルはRailsがデフォルトで用意してくれている

1. .gitattributes.gitignoreの2ファイルが現在srcファイル内にあるが、プロジェクトのディレクトリ直下に移動させる
terminal $ mv src/.gitignore . $ mv src/.gitattributes .

2. .gitを削除

  • git initをすると作られるが、こいつがsrcディレクトリ配下にもあり二重管理でエラーになってしまうので.gitファイルを削除する
$ rm -rf src/.git/
  • -rf・・・指定したディレクトリ以下全部のファイルを消す

3. ファイルを修正

  • すべてにsrcを付ける
    • srcディレクトリに入ってしまっている為、ディレクトリの構造を合わせる
  • src/db/mysql_dataも管理下から外す
    • mysqlの実行中のデータで、ソースコードとは関係がないファイルのため.gitignoreに追記する
    • src/db/mysql_datadocker-composeファイルのvolumesで指定している
.gitignore
src/.bundle

src/log/*
src/tmp/*
!src/log/.keep
!src/tmp/.keep

src/tmp/pids/*
!src/tmp/pids/
!src/tmp/pids/.keep

src/storage/*
!src/storage/.keep

src/public/assets
src/.byebug_history

src/config/master.key

src/public/packs
src/public/packs-test
src/node_modules
src/yarn-error.log
src/yarn-debug.log*
src/.yarn-integrity

4. add, commit, push

$ git status
$ git add .
$ git commit -m "first commit"
$ git branch -M main
$ git remote add origin https://github.com/Ryo-exid/rails-docker-gucci.git
$ git push -u origin main

pushの際にUsernameとPasswordの入力を求められる場合、Passwordにはアクセストークンを入力すよう注意する

GitHubへのアップ完了!👏

2. CI

テストコードを記載

src/test/controllers/homes_controller_test.rb
require "test_helper"

class HomesControllerTest < ActionDispatch::IntegrationTest
  test "the truth" do
    assert true
  end
end

CircleCIに登録

「GitHubで登録」を選ぶ

  • プロジェクトの登録も一緒に行う

configを設定

  • プロジェクトディレクトリ直下に.circleciディレクトリを作成し、その配下にconfig.ymlを作成
.circleci/config.yml
version: 2.1
orbs:
  ruby: circleci/ruby@1.1.2
  heroku: circleci/heroku@1.2.3

jobs:
  build:
    docker:
      - image: circleci/ruby:2.7
    working_directory: ~/rails-docker-gucci/src
    steps:
      - checkout:
          path: ~/rails-docker-gucci
      - ruby/install-deps

  test:
    docker:
      - image: circleci/ruby:2.7
      - image: circleci/mysql:5.5
        environment:
          MYSQL_ROOT_PASSWORD: password
          MYSQL_DATABASE: app_test
          MYSQL_USER: root
    environment:
      BUNDLE_JOBS: "3"
      BUNDLE_RETRY: "3"
      APP_DATABASE_HOST: "127.0.0.1"
      RAILS_ENV: test
    working_directory: ~/rails-docker-gucci/src
    steps:
      - checkout:
          path: ~/rails-docker-gucci
      - ruby/install-deps
      - run:
          name: Database setup
          command: bundle exec rails db:migrate
      - run:
          name: test
          command: bundle exec rake test

workflows:
  version: 2
  build_and_test:
    jobs:
      - build
      - test:
          requires:
            - build
  • 解説
    • orbs:は事前に定義したjobs:をシェアできるもの
    • 今回はbuild:test:というjobs:を定義
    • workflows:で今回build_test_and_deploy:というものを作っている
    • 構造としてはworkflows:が中心で、workflows:で定義された順番にjobs:の処理を行う

database.ymlのhostの値を書き換える

  • CircleCIだとdocker-composeを使っていない為、'db'という指定の仕方ができない
    • 環境変数のAPP_DATABASE_HOSTに値がsetされていたらそのままhostの値として使い、なかった時はdbを使用
    • ローカルではdocker-composeを使用する為、dbを取るようにしている
database.yml
test:
  <<: *default
  database: app_test
  host: <%= ENV.fetch("APP_DATABASE_HOST") { 'db' } %>

環境変数を設定

  • configディレクトリ配下にmaster.keyがあるのでそのファイルの中身の値を環境変数として設定
    • ソースコードを動かす上で必要な値が記されているが、流出するとまずいため.gitignoreに記載されている
$ heroku config:add RAILS_MASTER_KEY='master.keyから値をコピペ' -a アプリ名

GitHubにプッシュ

$ git switch -c ci
$ git branch # ciブランチにいることを確認
$ git add .
$ git commit -m "CircleCIが動くように、configファイルを設定"
$ git push origin ci

  • main←ciでプルリクを作成し、テストが通ったらマージ
    スクリーンショット 2022-09-23 18.45.24.png

  • mainブランチにpull

$ git switch main
$ git pull origin main

🎉🎉🎉pushされる度に自動テストが行われるCIが完成!!🎉🎉🎉

3. CD

トピックブランチ作成&移動

$ git switch -c cd
$ git branch -d ci # ciブランチはもう使わないので削除
$ git branch # cdにいること

configを修正

.circleci/config.yml
version: 2.1
orbs:
  ruby: circleci/ruby@1.1.2
  heroku: circleci/heroku@1.2.3

jobs:
  build:
    docker:
      - image: cimg/ruby:2.7.5
    working_directory: ~/rails-docker-gucci/src
    steps:
      - checkout:
          path: ~/rails-docker-gucci
      - ruby/install-deps

  test:
    docker:
      - image: cimg/ruby:2.7.5
      - image: circleci/mysql:5.5
        environment:
          MYSQL_ROOT_PASSWORD: password
          MYSQL_DATABASE: app_test
          MYSQL_USER: root
    environment:
      BUNDLE_JOBS: "3"
      BUNDLE_RETRY: "3"
      APP_DATABASE_HOST: "127.0.0.1"
      RAILS_ENV: test
    working_directory: ~/rails-docker-gucci/src
    steps:
      - checkout:
          path: ~/rails-docker-gucci
      - ruby/install-deps
      - run:
          name: Database setup
          command: bundle exec rails db:migrate
      - run:
          name: test
          command: bundle exec rake test

  deploy:
    docker:
      - image: circleci/ruby:2.7.5
    steps:
      - checkout
      - setup_remote_docker:
          version: 19.03.13
      - heroku/install
      - run:
          name: heroku login
          command: heroku container:login
      - run:
          name: push docker image
          command: heroku container:push web -a $HEROKU_APP_NAME
      - run:
          name: release docker image
          command: heroku container:release web -a $HEROKU_APP_NAME
      - run:
          name: database setup
          command: heroku run bundle exec rake db:migrate RAILS_ENV=production -a $HEROKU_APP_NAME

workflows:
  version: 2
  build_test_and_deploy:
    jobs:
      - build
      - test:
          requires:
            - build
      - deploy:
          requires:
            - test
          filters:
            branches:
              only: main

  • orbs:heroku: circleci/heroku@1.2.3を追加
  • workflowsdeploy:を追加
  • jobs:deployを追加

環境変数を設定

  • circleciにアクセス
    Projectsrails-docker-gucci(今回のプロジェクト)Project SettingsEnvironment VariablesAdd Environment Variable
    • config.ymlで使っていたHEROKU_APP_NAMEを設定
      スクリーンショット 2022-09-23 18.55.33.png
    • 動かす上でもうひとつHEROKU_API_KEYも設定
    • Name:HEROKU_API_KEY
    • Value:herokuにログインAccount Settings→少し下にスクロールし、API KeyをコピーしてValueに貼り付け

ローカルで起動するかどうか確認

$ docker-compose up -d

GitHubにプッシュ→プルリク作成→マージ

$ git add .
$ git commit -m "CD用の設定を追加"
$ git push origin cd
  • マージされたらデプロイされているかどうかを確認
    • CircleCI→Dashboard→All Pipelines→rails-docker-gucci
      スクリーンショット 2022-09-23 19.03.38.png

CircleCI上記ページ上のRerun workflow from start (こんな感じのボタン↩️)を押すともう一度build, test, deployが行われる

CircleCIでdeployがSuccessになってもHerokuへの反映には時間がかかる
その際はログ出力コマンドで状況を確認することも可能

  • ログ出力コマンド
$ heroku logs -t -a アプリ名

ブラウザから確認

$ heroku open -a アプリ名

スクリーンショット 2022-09-23 17.04.09.png

🎉🎉🎉自動テスト&自動デプロイ完了🎉🎉🎉

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