LoginSignup
9
8

More than 5 years have passed since last update.

Ansible を使って複数のリモートサーバに nginx で プロキシサーバを構築する

Last updated at Posted at 2014-08-09

目的

表題の通り、Ansible を使って複数のリモートサーバに nginx でプロキシサーバを構築する。今回はリモートサーバとして AWS の EC2 インスタンスを使用している。

やりたいこと

  • 複数の EC2 インスタンスに 1 コマンドでサーバ構築する。
  • インスタンスを追加するときは対象の IP アドレスを追記するだけ。

やること

ansible コマンド実行時にすること。

  1. nginx をインストール。
  2. nginx の設定ファイルを記述。
  3. nginx を起動。
  4. 1.~3. を複数のインスタンスに対して 1 コマンドで実行。

インストール

実行するローカル環境にインストール。
これで ansible-playbook というコマンドが使用できるようになる。

$ pip install ansible

設定ファイルを書く

ディレクトリ構造

.
|-- webapp.yml
|-- hosts
|-- nginx.conf
`-- myapp.j2

nginx の設定ファイル

myapp.j2
server {
    listen       80;
    server_name  0.0.0.0;

    location / {
        proxy_pass {{ proxy_pass }};
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_cache zone1;
        proxy_cache_key $proxy_host$uri$args;
        proxy_cache_valid 600s;
    }
}

同じディレクトリに nginx.conf を用意。

ansible の設定ファイル

webapp.yml

- hosts: web-servers
  user: ec2-user
  sudo: True

  vars:
    proxy_pass: '<オリジンの URL>'

  tasks: 
  # nginx をインストールする。
  - name: Install nginx
    yum: name=nginx state=latest
  # cache ディレクトリを作成する。
  - name: Create Cache
    action: file dest=/var/cache/nginx/cache state=directory owner=nginx group=nginx
  # ローカルの ngnix.conf をリモートにコピーする。
  - name: Copy the default nginx config file
    action: copy src=./nginx.conf dest=/etc/nginx/nginx.conf
  # ローカルの myapp.j2 を myapp.conf にコンパイルしてリモートにコピーする。
  - name: Write the original nginx config file
    action: template src=./myapp.j2 dest=/etc/nginx/conf.d/myapp.conf
    # nginx を起動する。
    notify:
    - Start nginx
  handlers:
    - name: Start nginx
      action: service name=nginx state=restarted

対象のホストを記述する

[web-servers]
54.64.xxx.xxx
54.64.yyy.yyy
54.64.zzz.zzz

実行

$ ansible-playbook ./webapp.yml --private-key ~/.ssh/mykey.pem -i ./hosts

Ansible を使ってみて

Web サーバを起動するくらいのシンプルな構成ならば Ansible ならシンプルに書けますし、対象のリモートサーバを追加する場合は hosts ファイルに追記するだけなので、丁度やりたかったことが最速でできました:)
Python のライブラリですが、記述するのが yaml と ini ファイルライクな hosts ファイルだけ、というのも魅力ですね。
チュートリアルなど見ながら私でも 3 時間くらいでできたのでオススメです:D

9
8
0

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
9
8