概要
状況
- ウェブサービスが自前サーバー(以下プロダクションサーバー)にデプロイされている
- 毎回デプロイコマンドを手動で叩いている
- 踏み台のsshサーバーがある
実現したこと
Githubでmasterブランチが更新されたら,CircleCIを使って自前サーバーのウェブサービスをデプロイする.
参考
https://www.wantedly.com/companies/union-tec/post_articles/246114
https://circleci.com/docs/2.0/deployment-examples/index.html#ssh
https://circleci.com/docs/2.0/add-ssh-key/
手順
1. ssh keyの追加
踏み台サーバーとプロダクションサーバーそれぞれのssh keyを登録しなければならない.
以下の手順はそれぞれのサーバーについて行う.
1.1 公開鍵と秘密鍵の作成
公開鍵と秘密鍵を作成する.
$ ssh-keygen -m PEM -t rsa -C "コメント"
この後保存先を聞かれるが,適当に id_circleci_rsa
で保存した.
パスフレーズは作らないのでそのままenterを2回押す.
1.2 サーバーのauthorized_keysに追加
先ほど作成した公開鍵(id_circleci_rsa.pub
)と秘密鍵(id_circleci_rsa
)のうち,公開鍵を登録する.
$ cat .ssh/id_circleci_rsa.pub >> .ssh/authorized_keys
これをしないとsshした時にパスワードを聞かれる.
1.3 CirlcleCIにssh key登録
秘密鍵の方はCircleCIに登録する.
CircleCIのプロジェクトにいき,project settings > ssh keys で-----BEGIN RSA PRIVATE KEY-----
から始まる秘密鍵を登録する.
$ cat .ssh/id_cricleci_rsa | pbcopy # クリップボードにコピー
登録するとfingerprintがそれぞれ発行される.
1.4 鍵削除
ここまでで踏み台サーバーとプロダクションサーバー上の鍵は必要なくなったので
rm .ssh/id_circleci_rsa .ssh/id_circleci_rsa.pub
しておく.
2. ssh configを作成
.circleci/circleci_ssh_config
をこの記事のように作成.
3. .circleci/config.ymlの編集
今までbuild
しか書いていなかったので,その下に追記した.
jobs:
build:
...
-- ここから先を追記 --
deploy:
machine:
enabled: true
steps:
- checkout
- add_ssh_keys:
fingerprints:
- "踏み台サーバーのfingerprint"
- "プロダクションサーバーのfingerprint"
- run:
name: Add ssh config
command: cat ~/project/.circleci/circleci_ssh_config >> ~/.ssh/config
- run:
name: Deploy Over SSH
command: |
ssh production "デプロイコマンド(git pull && deploy的な)"
workflows:
version: 2.1
build-and-deploy:
jobs:
- build
- deploy:
requires:
- build # only deploy once build job has completed
filters:
branches:
only: master # only deploy on the master branch
4. その他
私の環境では3まででデプロイできなかったのでその他の設定を行った.
4.1 deploy keyをgithubに登録
githubリポジトリにプロダクションサーバーのdeploy keyを登録する.
プロダクションサーバー上で1.1と同じようにssh-keygen
で公開鍵と秘密鍵を作り,公開鍵の方をgithubリポジトリのSettings > Deploy keysに登録する.
登録すると,git pull
やgit clone
をする時にパスワードを聞かれなくなる.
4.2 dockerとdocker-composeのシンボリックリンク
ssh
経由でdocker
やdocker-compose
を叩こうとするとcommand not found
になってしまう.
そこで,プロダクションサーバーで以下のようなシンボリックリンクを貼る:
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo ln -s /usr/local/bin/docker /usr/bin/docker
/usr/local/binではなく/usr/binを見にいってるのかしら...よく分からない.
以上で無事自動デプロイ出来た.