DTI VPS上にLINE BOTを置いています。LINE BOTサーバはuWSGIアプリとしてPythonで作っています。今回、Ansibleを使って基本的なuWSGIサーバの構築までは自動でやろうと考え、その仕組みを考えてみました。以下にその結果を挙げます。
全ソースは以下のgitリポジトリにあります。
https://github.com/tacchang001/linebot_provisioning
https://github.com/tacchang001/bot_fx_helloworld
この例では、192.168.56.111という仮想マシンをVPSに見立ててVirtualBoxの仮想マシンとして使います。
Ubuntu 14.04の仮想マシンとして、sshのための公開鍵のコピーまでは手動でやってあります。
ssh-copy-id -i ~/.ssh/公開鍵.pub ユーザ@192.168.56.111
.
├── roles
│ ├── base
│ │ ├── tasks
│ │ │ └── main.yml
│ │ └── vars
│ │ └── main.yml
│ ├── build_site
│ │ ├── tasks
│ │ │ └── main.yml
│ │ └── vars
│ │ └── main.yml
│ ├── check-nginx
│ │ ├── tasks
│ │ │ └── main.yml
│ │ └── vars
│ │ └── main.yml
│ └── nginx
│ ├── tasks
│ │ └── main.yml
│ └── vars
│ └── main.yml
└── targets
├── dev
│ ├── ansible.cfg
│ ├── check.sh
│ ├── files
│ │ ├── bot_fx_helloworld.conf
│ │ └── bot_fx_helloworld.nginx
│ ├── hosts
│ ├── main.yml
│ ├── play.sh
│ └── vars
│ └── site.yml
└── prod
ソースの解説
targets/dev/main.yml
セットアップは、大きく分けて①基本パッケージのインストール(base)、②サイトコード(今回はbot_fx_helloworld)をダウンロード(build_site)、③nginxに組み込む(nginx)という順番で構築します。
#
- hosts: test-server
# gather_facts: false
remote_user: "{{ user_to_work }}"
# become: yes
become_method: sudo
vars_files:
- vars/site.yml
roles:
- { role: base, become: yes }
- { role: build_site, become: no }
- { role: nginx, become: yes }
- { role: check-nginx, become: yes }
roles/build_site/tasks/main.yml
LINE BOTのサイトは頻繁に更新することを想定して、サイトの基本を構築する手順とは別にしています。
LINE BOTのサイトは、Python 3.4下で運用する(好み)ので、Pythonの仮想環境を作ってそこで運用します。必要なPythonパッケージ(Flask等)は、requirements.txtに列挙されている前提です。
- name: Pythonの仮想環境を作成
command: virtualenv /home/{{ ansible_ssh_user }}/{{ venv_name }} -p python{{python_version}} creates='/home/{{ ansible_ssh_user }}/{{ venv_name }}'
- stat: path=/home/{{ ansible_ssh_user }}/{{ app_name }}
register: f
- name: (サンプル)サイト・プロジェクトをgit cloneする
git:
repo: git@github.com:{{ github_user }}/{{ app_name }}.git
dest: /home/{{ ansible_ssh_user }}/{{ app_name }}
accept_hostkey: yes
- name: サイト構築に必要なパッケージをインストール。requirements.txtに列挙されている前提
pip:
requirements: /home/{{ ansible_ssh_user }}/{{ app_name }}/requirements.txt
virtualenv: /home/{{ ansible_ssh_user }}/{{ venv_name }}
virtualenv_python: python{{python_version}}
手順を構築するまで
手順のベースは、brennv/flask-ansible-exampleを参考にさせてもらいました。
githubからcloneで、Permission deniedエラー
githubからcloneする際、以下のエラーに遭遇しました。
Warning: Permanently added 'github.com,192.30.253.113' (RSA) to the list of known hosts.
kaito__さんのサイトを参考にさせてもらい解決しました。
[defaults]
transport = ssh
become_flags = -HEs