EC2インスタンスの初期設定を自動化する。

こんにちは、NowTomです。前回は、EC2で実際にインスタンスを作成して、Ubuntuを動かすところまでやってみました。インスタンスを作成したら、自分がやりたいことに沿ってサーバを設定していきます。設定の仕方は、サーバにログインして手動でパッケージのインストールなどをしてくと思いますが、これだと後で同じ環境をもう一台欲しくなったときなどにすぐに用意することが難しいと思います。そこで、今回はサーバの設定作業を自動化して、すぐに欲しい環境が整ったサーバを用意できるような仕組みをご紹介します。※今回はRubyを使いますので、インストールしている必要があります。私は、ruby=1.9.2、gem=1.3.7を利用しています。

今回やること

  1. インスタンスを作成する
  2. 手動で環境を整える
  3. Capistranoを使って自動で環境を整える

インスタンスを作成する

まずは、インスタンスを作成しましょう。前回を参考にして、東京リージョンにMicroインスタンスUbuntuを作成します。

$ ec2-run-instances ami-440fa445 --instance-type t1.micro --region ap-northeast-1 -k sample-keypair -g sample_security_group

作成されたインスタンスに接続するために、DNSを調べます。

$ ec2-describe-instances --region ap-northeast-1
RESERVATION	xxxxxxxxxx	xxxxxxxxxxxx	xxxxxxxxxxxxxxx
INSTANCE	i-40a5ca41	ami-440fa445	xxxxx.ap-northeast-1.compute.amazonaws.com

上記の「xxxxx.ap-northeast-1.compute.amazonaws.com」に、sshで接続に行けばよいです。これでインスタンスの準備は完了です。

手動で環境を整える

やることを洗い出す

まずは、サーバをどのような目的で使うかを決めます。今回は、Webサーバとして使う前提にします。
そうしたら、Webサーバとして使うには、どのような設定作業が必要か出してみます。
初期設定でとりあえず動くようにするとしたら、下記の2つくらいでしょうか。

  1. apacheのインストール
  2. apacheの起動

apacheのインストールを行う前に、Linux自体の更新も行なっておこうと思いますので、
2つの作業を追加しようと思います。

  1. apt-get updateの実行
  2. apt-get upgradeの実行
  3. apacheのインストール
  4. apacheの起動
手動でやることを実行する

それでは、実際に設定作業を行います。サーバにSSHでログインします。

$ ssh -i $AWS_HOME/keypair.pem ubuntu@xxxxx.ap-northeast-1.compute.amazonaws.com
Linux ip-xxx-xxx-xxx-xxx 2.6.35-24-virtual #42-Ubuntu SMP Thu Dec 2 05:01:52 UTC 2010 i686 GNU/Linux
Ubuntu 10.10

Welcome to Ubuntu!
 * Documentation:  https://help.ubuntu.com/

1. apt-get updateの実行

$ sudo apt-get update

2. apt-get upgradeの実行

$ sudo apt-get upgrade

3. apacheのインストール(-yオプションをつけること)

$ sudo apt-get install -y apache2

4. apacheの起動
インストールしたら、勝手に上がってたのでこれはいらないようです。

$ ps -ef | grep apache
root      1177     1  0 03:53 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1181  1177  0 03:53 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1182  1177  0 03:53 ?        00:00:00 /usr/sbin/apache2 -k start
www-data  1183  1177  0 03:53 ?        00:00:00 /usr/sbin/apache2 -k start
ubuntu    1275   715  0 04:00 pts/0    00:00:00 grep --color=auto apache

ブラウザから「xxxxx.ap-northeast-1.compute.amazonaws.com」にアクセスするとapacheのIt works!画面がでるはずです。
繋がらない場合は、AWSマネジメントコンソールからセキュリティグループの設定を確かめてください。
HTTPの接続を許す必要があります。

Capistranoを使って自動で環境を整える

設定作業がわかったら、いよいよ自動化をします。自動化するには、Capistranoというツールを使います。

Capistranoの概要

Capistranoは、Rubyでできていて、Railsを作った37signalsが作ったそうです。
主な用途としては、Railsアプリケーションをデプロイするのに使います。
SSHで接続して、コマンドを実行してくれるのでなんでもできますw
私はこれを悪用?して、環境構築の自動化に使いたいと思います。(環境構築には、Chefなどのツールを使うそうです。)

インストール

Capistranoは、gemで配られているので下記のコマンドでインストールできます。

$ gem install capistrano
初期設定

Capistranoをインストールしたら、適当な場所で以下のコマンドを実行して、設定ファイルを作成します。

$ capify .
[add] writing './Capfile'
[add] making directory './config'
[add] writing './config/deploy.rb'
[done] capified!

1つのディレクトリとファイルが2つ作成されました。「config/deploy.rb」のほうを修正して、自動化する内容を追記します。
初期状態は以下のとおり。

set :application, "set your application name here"
set :repository,  "set your repository location here"

set :scm, :subversion
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`, `subversion` or `none`

role :web, "your web-server here"                          # Your HTTP server, Apache/etc
role :app, "your app-server here"                          # This may be the same as your `Web` server
role :db,  "your primary db-server here", :primary => true # This is where Rails migrations will run
role :db,  "your slave db-server here"

# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts

# If you are using Passenger mod_rails uncomment this:
# namespace :deploy do
#   task :start do ; end
#   task :stop do ; end
#   task :restart, :roles => :app, :except => { :no_release => true } do
#     run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
#   end
# end%
テスト

簡単なテストとして、最初に用意したインスタンスに繋いでechoコマンドを行うタスクを作ってみます。

set :application, "sample"

set :user, "ubuntu"

# runを実行したときに、デフォルトでsudoを使わないようにする。
set :use_sudo, false

# インスタンスを作成したときに使ったキーを指定する。
ssh_options[:keys] = [File.join("/home/nowtom/.aws", "sample-keypair.pem")]

# 接続するサーバを指定する。IPアドレスでもよい。
role :test, "xxxxx.ap-northeast-1.compute.amazonaws.com"

task :echo, :roles => :test do
  run "echo RUN"
  sudo "echo SUDO"
end

タスクを実行します。

$ cap echo
* executing `echo'
* executing "echo RUN"
servers: ["xxxxx.ap-northeast-1.compute.amazonaws.com"]
[xxxxx.ap-northeast-1.compute.amazonaws.com] executing command
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] RUN
command finished in 835ms
* executing "sudo -p 'sudo password: ' echo SUDO"
servers: ["xxxxx.ap-northeast-1.compute.amazonaws.com"]
[xxxxx.ap-northeast-1.compute.amazonaws.com] executing command
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] SUDO
command finished in 42ms

いよいよ、環境構築のタスクを作ります。

task :setup, roles => :test do
  sudo "apt-get update"
  sudo "apt-get upgrade -y"
  sudo "apt-get install -y apache2"
end

環境構築タスクを実行します。(結構時間がかかります。)

$ cap setup
* executing `setup'
* executing "sudo -p 'sudo password: ' apt-get update"
servers: ["xxxxx.ap-northeast-1.compute.amazonaws.com"]
[xxxxx.ap-northeast-1.compute.amazonaws.com] executing command
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] 0% [Working]
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] 0% [Waiting for headers] [Connecting to security.ubuntu.com (91.189.92.167)]
command finished in 11134ms
* executing "sudo -p 'sudo password: ' apt-get upgrade -y"
servers: ["xxxxx.ap-northeast-1.compute.amazonaws.com"]
[xxxxx.ap-northeast-1.compute.amazonaws.com] executing command
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Reading package lists... 0%
'Reading package lists... Donep-northeast-1.compute.amazonaws.com] Reading package lists... 100%$'
command finished in 146271ms
* executing "sudo -p 'sudo password: ' apt-get install -y apache2"
servers: ["xxxxx.ap-northeast-1.compute.amazonaws.com"]
[xxxxx.ap-northeast-1.compute.amazonaws.com] executing command
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Reading package lists... Done
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Building dependency tree
'Reading state information... Donertheast-1.compute.amazonaws.com] Reading state information... 0%$'
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] The following extra packages will be installed:
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] apache2-mpm-worker apache2-utils apache2.2-bin apache2.2-common libapr1
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap ssl-cert
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Suggested packages:
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] apache2-doc apache2-suexec apache2-suexec-custom openssl-blacklist
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] The following NEW packages will be installed:
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] apache2 apache2-mpm-worker apache2-utils apache2.2-bin apache2.2-common
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] libapr1 libaprutil1 libaprutil1-dbd-sqlite3 libaprutil1-ldap ssl-cert
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] 0 upgraded, 10 newly installed, 0 to remove and 2 not upgraded.
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Setting up apache2-mpm-worker (2.2.16-1ubuntu3.1) ...
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] * Starting web server apache2       $''[80G
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Setting up apache2 (2.2.16-1ubuntu3.1) ...
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Setting up ssl-cert (1.0.26) ...
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] Processing triggers for libc-bin ...
** [out :: xxxxx.ap-northeast-1.compute.amazonaws.com] ldconfig deferred processing now taking place
command finished in 41212ms

これで簡単ではありますが、環境構築の自動化ができました。

最後に

今回はEC2にインスタンスを作成して、Capistranoを使ってApacheがインストールされたサーバを構築する方法をご紹介しました。
次回は、まだ未定ですが、EC2の機能かEC2を利用して環境構築をする方法をご紹介したいと思います。