LoginSignup
112
119

More than 3 years have passed since last update.

CircleCIからCapistranoを利用してAWS(EC2)にデプロイする

Last updated at Posted at 2014-10-03

CircleCIからEC2上に構築しているサーバにデプロイする方法です

前提

  • ローカルなどからcapistranoでデプロイできる状態

準備

セキュリティグループ

SSHをセキュリティグループで制限している場合、CircleCI上からのアクセスを許可しなくてはなりません

VPC

VPCでは他セキュリティグループからの許可ができません

CircleCIはEC2 US East region上に構築されているのでそのIPを全部許可すればよいのですが現実的ではありません(よね?)

AWS CLIを使ってビルドの開始時にコンテナのIPをSSH許可して、終了時にSSH許可を取り消す事で対応します

SSH許可

aws ec2 authorize-security-group-ingress --group-id $MYSECURITYGROUP --protocol tcp --port 22 --cidr $MYIP/32

SSH許可を取り消し

aws ec2 revoke-security-group-ingress --group-id $MYSECURITYGROUP --protocol tcp --port 22 --cidr $MYIP/32

VPC以外

VPC環境で構築していない場合は、CircleCIのセキュリティグループのIDが公開されていますのでAWSで別のアカウントのセキュリティグループを使うを参考にしてアクセスを許可してください

秘密鍵の設定

EC2にログインする為の秘密鍵を設定してください

Project Settings -> SSH keysから設定できます

設定した秘密鍵はビルド時に自動的にssh-agentに追加されます

またGitHubへのアクセスもssh-agentを利用している場合はGitHubへアクセスできる秘密鍵も設定してください

AWS CLI

CircleCI上にインストールされているAWS CLIはバージョンが古い為、以下のエラーが出てしまいます

--group-id: mispelled meta parameter?

dependenciesで最新版をインストールする事で回避できます

dependencies:
  pre:
    - sudo pip install awscli

環境変数

AWSにアクセスする為に必要な環境変数を設定してください

  • AWS_ACCESS_KEY_ID - アクセスキーID
  • AWS_SECRET_ACCESS_KEY - 秘密アクセスキー

環境変数はProject Settings -> Environment vairablesで設定できます

サンプル

circle.yml

masterにpush時にstagingにデプロイするサンプルです

circle.yml
machine:
  ruby:
    version:
      2.1.2

dependencies:
  pre:
    - sudo pip install awscli

test:
  override:
    - bundle exec rake rubocop
    - bundle exec rake spec

deployment:
  staging:
    branch: master
    commands:
      - sh script/deploy_staging.sh

script/deploy_staging.sh

#!/bin/sh

export AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID}
export AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY}
export AWS_DEFAULT_REGION="ap-northeast-1"

MYSECURITYGROUP=”セキュリティグループID"
MYIP=`curl -s ifconfig.me`

aws ec2 authorize-security-group-ingress --group-id $MYSECURITYGROUP --protocol tcp --port 22 --cidr $MYIP/32
bundle exec cap staging deploy
aws ec2 revoke-security-group-ingress --group-id $MYSECURITYGROUP --protocol tcp --port 22 --cidr $MYIP/32

Links

以上

112
119
1

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
112
119