AWSのEC2に適当に実験アプリを作るためのセットアップスクリプト

いろいろとひどい感じだし「イメージで持っておけばいいじゃない」とか「yum groupinstallで"Development Tools"入れないの?」とかあるだろうけど、後でごにょる用にメモ。各所オレオレ仕様。


ruby1.9 + passenger + nginx + padrino(sinatra)な環境。


実際に実験に使ったAMIは「Amazon Linux AMI 2013.03」。
インスタンス新規作成後に「sudo yum update」のみ実行した状態で以下をシェルスクリプトとして作成してユーザ「ec2-user」がsudoで実行することを想定。
最低限「sample.example.com」のところだけ自前のホスト名にする必要あり。
80番ポートでアクセスするとnginxのデフォルトページが出る。
8080番ポートで「favicon.ico」にアクセスすると変なアイコンが出る。


「/etc/init.d/nginx」の冒頭にいる「xxx」の群れは外部サービスのアクセスキーを環境変数で使うことを想定。Herokuなんかに載せたときに「heroku config:add 【環境変数名】=【値】」とかやって設定するイメージ。


「tilt」の「1.3.7」を明示しているところは現在のpadrino用の調整なのですぐに陳腐化すると思われる。
また、nginx内の「Passenger」のバージョンを明示しているあたりも変化するので注意。


「/opt/nginx/conf/sites-available」は存在する設定、「/opt/nginx/conf/sites-enabled」は有効な設定という扱い。前者に設定の実体を作っておき、有効なもののみ後者にシンボリックリンクを作成するという想定。会社の人のやり方をそのまま拝借した。


エラーチェックしてないので「generate sample application」とか相対パスでガシガシやってるあたりは注意。

#!/bin/sh

# test target AMI : Amazon Linux AMI 2013.03
# 1. Launch new instance.
# 2. login as ec2-user.
# 3. "sudo yum update"
# 4. "vi ~/setup-application" and ":set paste" and paste this code.
# 5. change "sample.example.com" to your hostname and save the script.
# 6. "chmod 755 ~/setup-application"
# 7. "sudo ~/setup-application"

if [ $UID -ne 0 ]; then
  echo "Please use sudo."
  exit 1
fi

# ruby 1.8 -> 1.9 (append package and replace symbolic link)
# recommend to use rbenv
yum install -y ruby19 ruby19-devel
for f in /usr/bin/*1.9
do
  ln -fs $f ${f%1.9}
done

# install passenger
gem install passenger --no-ri --no-rdoc

# install development tools
yum -y install gcc gcc-c++ make curl-devel openssl-devel zlib-devel

# install nginx
/usr/local/bin/passenger-install-nginx-module --auto --prefix=/opt/nginx --auto-download --extra-configure-flags=--with-http_ssl_module

# configure nginx
cp -p /opt/nginx/conf/nginx.conf /opt/nginx/conf/nginx.conf.orig
cat << '_EOF_' > /opt/nginx/conf/nginx.conf
worker_processes  1;
events {
  worker_connections  1024;
}
http {
  passenger_root /usr/local/share/gems/gems/passenger-4.0.2;
  passenger_ruby /usr/bin/ruby1.9;
  include       mime.types;
  default_type  application/octet-stream;
  sendfile           on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  localhost;
    location / {
      root   html;
      index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   html;
    }
  }
  include /opt/nginx/conf/sites-enabled/*;
}
_EOF_
mkdir -p /opt/nginx/conf/sites-enabled
mkdir -p /opt/nginx/conf/sites-available

# create init.d script for nginx
cat << '_EOF_' > /etc/init.d/nginx
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /opt/nginx/conf/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

# Export account data.
export TWITTER_CONSUMER_KEY=xxx
export TWITTER_CONSUMER_SECRET=xxx
export FACEBOOK_APP_ID=xxx
export FACEBOOK_APP_SECRET=xxx
export MONGO_HOST=xxx
export MONGO_PORT=xxx
export MONGO_USER=xxx
export MONGO_PASS=xxx
export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxx
export S3_BUCKET_NAME=xxx

nginx="/opt/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`$nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    #make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac
_EOF_
chmod 755 /etc/init.d/nginx
chkconfig nginx on

# install git and padrino and application dir
yum install -y git
gem install bundler --no-ri --no-rdoc
gem install padrino --no-ri --no-rdoc
mkdir /opt/webapp

# generate sample application
cd /opt/webapp
/usr/local/bin/padrino g project sample
cd sample
mkdir -m 777 log
touch tmp/restart.txt

# https://github.com/padrino/padrino-framework/issues/1274
echo "gem 'tilt', '1.3.7'" >> Gemfile

cat << '_EOF_' > _initialize.sh
#!/bin/sh
/usr/local/bin/bundle install --path vendor/bundle
_EOF_

cat << '_EOF_' > _route.sh
#!/bin/sh
/usr/local/bin/bundle exec padrino rake routes
_EOF_

cat << '_EOF_' > _spec.sh
#!/bin/sh
/usr/local/bin/bundle exec padrino rake spec
_EOF_

chmod 755 _initialize.sh _route.sh _spec.sh
./_initialize.sh

chown -R ec2-user:ec2-user /opt/webapp/sample

# configure sample application
cat << '_EOF_' > /opt/nginx/conf/sites-available/sample
  server {
    listen 8080;
    server_name sample.example.com;
    location / {
      root /opt/webapp/sample/public;
      index index.html index.htm;
      passenger_enabled on;
    }
  }
_EOF_
ln -s /opt/nginx/conf/sites-available/sample /opt/nginx/conf/sites-enabled/sample

# start nginx
service nginx start