ウェブサービスを作っています。

CircleCI 2.0 + Capistrano で自動デプロイ

CircleCI 2.0 で、Rails アプリを自動デプロイする設定例です。

ミドルウェアとして、MySQL と Elasticsearch を使用しています。

2017/11/30 現在の情報となります。


.circleci/config.yml (インデントが 4 スペースの場合があるので注意)

ruby_image: &ruby_image
  circleci/ruby:2.4.2

bundle_cache_key: &bundle_cache_key
  bundle-{{ checksum "Gemfile.lock" }}

version: 2

jobs:
  build:
    docker:
      - image: *ruby_image
        environment:
          DATABASE_URL: "mysql2://root@127.0.0.1/circle_test"
          RAILS_ENV: test
      - image: circleci/mysql:5.7
      - image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
        environment:
          xpack.security.enabled: false

    steps:
      - checkout

      - restore_cache:
          key: *bundle_cache_key

      - run:
          name: Bundle Install
          command: bundle install --jobs=4 --retry=3 --path vendor/bundle

      - save_cache:
          key: *bundle_cache_key
          paths:
            - vendor/bundle

      - run:
          name: Wait for DB
          command: dockerize -wait tcp://localhost:3306 -timeout 1m

      - run:
          name: Wait for Elasticsearch
          command: dockerize -wait tcp://localhost:9200 -timeout 1m

      - run: bin/rails db:schema:load --trace

      - run: bundle exec rspec --format progress

  deploy:
    docker:
      - image: *ruby_image

    steps:
      - checkout

      - restore_cache:
          key: *bundle_cache_key

      - run:
          name: Deploy
          command: |
            bundle config --local path vendor/bundle
            .circleci/deploy.sh

workflows:
  version: 2

  build-and-deploy:
    jobs:
      - build
      - deploy:
          requires:
            - build
          filters:
            branches:
              only: master

.circleci/deploy.sh (実行権限をつける)

#!/bin/bash

set -ex

cat <<EOF >> $HOME/.ssh/config
Host xxx
  HostName xxx.xxx.xxx.xxx
  User xxx
  ...
EOF

bundle exec cap production deploy

あとは CircleCI のプロジェクト設定で、SSH 鍵の設定を行います。