Provisioning Servers for Rails with Ansible
Learning Ansible by building a server for a Rails app on a throwaway Vagrant VM, then applying the same playbook to EC2.
This post was originally published in Japanese on Qiita.
This is part 1 of 2. Part 2, Deploying a Rails App with Capistrano, deploys a Rails app to the servers built here.
What is Ansible?
Ansible is a configuration management tool. You write the state you want each server to be in, such as which packages are installed and which files are in place, in YAML files called playbooks. When you run a playbook, Ansible connects to each server over SSH and changes whatever doesn’t match what the playbook describes.
Ansible’s modules are idempotent: running the same playbook once or ten times leaves the server in the same state. A task whose result is already in place is reported as ok and left alone, and only what differs is changed. Apply the same playbook to the dev VM and to EC2, and everything it manages ends up the same on both.
Goals
- Run Ansible directly from the local machine
- Targets: a Vagrant VM for verification (dev) and EC2
- Prepare both servers for a Rails app: Ruby via rbenv and nginx
I had no infrastructure background, so setting up a web server was a real struggle. I built the configuration by trial and error on the dev VM: write Ansible code → run it against the dev VM → deploy the app with Capistrano (part 2) → fail → destroy the VM → create a fresh one → write Ansible code again. Because the VM can be thrown away at any time, a broken server only costs a rebuild, and every rebuild tests the playbook on a clean machine.
Setup
Create the dev VM
Ideally the dev VM runs the same OS as production. Production is Amazon Linux, but Amazon Linux only runs on EC2, so there’s no Vagrant box for it. CentOS is the closest match, since both come from Red Hat Enterprise Linux. I also wanted a box from a source I could trust, because a box is a full OS image and anyone can publish one. So I used the CentOS box provided by the National Renewable Energy Laboratory (NREL).
vagrant box add centos64 http://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.4-x86_64-v20131103.box
vagrant init centos64
config.vm.define :dev do |dev|
dev.vm.box = "centos64"
dev.vm.network :private_network, ip: "192.168.33.12"
end
vagrant up dev
Install Ansible on the local machine
brew install ansible
# or: sudo pip install ansible
ansible --version
ansible 1.7
Create the inventory file
The inventory lists the servers Ansible manages, grouped by name. Here there are two groups: dev for the Vagrant VM and prod for EC2.
[dev]
192.168.33.12 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.vagrant.d/insecure_private_key
[prod]
54.xxx.xxx.xxx ansible_ssh_user=ec2-user ansible_ssh_private_key_file=~/.ssh/aws.pem
Connection test
ansible all -i hosts -m ping
192.168.33.12 | success >> {
"changed": false,
"ping": "pong"
}
54.xxx.xxx.xxx | success >> {
"changed": false,
"ping": "pong"
}
How the playbook is organized
All the Ansible files live in one directory:
provisioning/
├── hosts
├── rails.yml
├── group_vars/
│ ├── all
│ ├── dev
│ └── prod
└── roles/
├── common/
│ ├── files/iptables-save
│ ├── handlers/main.yml
│ └── tasks/main.yml
├── nginx/
│ ├── handlers/main.yml
│ ├── tasks/main.yml
│ └── templates/default.conf
└── ruby/
├── files/rbenv.sh
└── tasks/main.yml
The playbook, rails.yml, says which roles to apply to which servers:
---
- name: Install ruby and nginx
hosts: all
sudo: yes
roles:
- common
- nginx
- ruby
hosts: all targets every server in the inventory. sudo: yes runs tasks as root unless a task says sudo: no. Each role is a directory of tasks for one job:
common: firewall rules that allow only SSH (22) and HTTP (80), the timezone, the EPEL repository, build tools, and/var/wwwfor the appnginx: installs nginx and its configruby: rbenv (a Ruby version manager) and ruby-build (its plugin that compiles Ruby), Ruby 2.1.3, and Bundler
Variables
The dev VM logs in as vagrant and EC2 as ec2-user, so their home directories differ. A file in group_vars/ named after an inventory group applies to the servers in that group:
login_user: vagrant
login_user: ec2-user
group_vars/all applies to every server and builds paths from that variable:
ruby_version: 2.1.3
rbenv_root: /home/{{ login_user }}/.rbenv
rbenv_root becomes /home/vagrant/.rbenv on the dev VM and /home/ec2-user/.rbenv on EC2.
Templates and handlers
---
# copied from https://github.com/ansible/ansible-examples/blob/master/wordpress-nginx/roles/nginx/tasks/main.yml
- name: Install nginx
yum: name=nginx state=present
- name: Copy nginx configuration
template: src=default.conf dest=/etc/nginx/conf.d/default.conf
notify: restart nginx
---
- name: restart nginx
service: name=nginx state=restarted
template copies a file from the role’s templates/ directory to the server, filling in any {{ }} variables on the way. notify queues a handler, and the handler runs once at the end of the play, only if the task actually changed something.
Keeping shell tasks idempotent
Most modules are idempotent on their own: yum skips a package that’s already installed, and template skips a file that hasn’t changed. shell and command aren’t. Ansible can’t tell what they do, so they run every time. To keep rbenv install from recompiling Ruby on every run, the ruby role checks first:
- name: check ruby installed
sudo: no
shell: rbenv versions | grep {{ ruby_version }}
register: ruby_installed
ignore_errors: yes
- name: install ruby
sudo: no
shell: rbenv install {{ ruby_version }}
when: ruby_installed|failed
register saves the result of the check, ignore_errors: yes keeps a failed check from stopping the play, and when runs the install only if the check failed. ruby-build is installed the same way.
Running it on the dev VM
--limit dev runs it on the dev VM only:
ansible-playbook -i hosts rails.yml --limit dev
PLAY [Install ruby and nginx] *************************************************
GATHERING FACTS ***************************************************************
ok: [192.168.33.12]
TASK: [common | Set up iptables rules] ****************************************
changed: [192.168.33.12]
TASK: [common | Change localtime to JST] **************************************
changed: [192.168.33.12]
TASK: [common | Add the EPEL software repository] *****************************
changed: [192.168.33.12]
TASK: [common | Install build depends] ****************************************
changed: [192.168.33.12] => (item=gcc,gcc-c++,git,make,tar,vim)
TASK: [common | Create /var/www directory] ************************************
changed: [192.168.33.12]
TASK: [nginx | Install nginx] *************************************************
changed: [192.168.33.12]
TASK: [nginx | Copy nginx configuration] **************************************
changed: [192.168.33.12]
TASK: [ruby | install build depends] ******************************************
changed: [192.168.33.12] => (item=openssl-devel,readline-devel,zlib-devel,mysql-devel)
TASK: [ruby | clone rbenv repo] ***********************************************
changed: [192.168.33.12]
TASK: [ruby | add rbenv initialization to profile] ****************************
changed: [192.168.33.12]
TASK: [ruby | check ruby-build installed] *************************************
failed: [192.168.33.12] => {"changed": true, "cmd": ["test", "-x", "/usr/local/bin/ruby-build"], "delta": "0:00:00.011944", "end": "2014-10-03 15:17:05.416544", "rc": 1, "start": "2014-10-03 15:17:05.404600"}
...ignoring
TASK: [ruby | clone ruby-build repo] ******************************************
changed: [192.168.33.12]
TASK: [ruby | install ruby-build] *********************************************
changed: [192.168.33.12]
TASK: [ruby | check ruby installed] *******************************************
failed: [192.168.33.12] => {"changed": true, "cmd": "rbenv versions | grep 2.1.3", "delta": "0:00:00.040867", "end": "2014-10-03 15:17:41.363395", "rc": 1, "start": "2014-10-03 15:17:41.322528"}
...ignoring
TASK: [ruby | install ruby] ***************************************************
changed: [192.168.33.12]
TASK: [ruby | set global ruby] ************************************************
changed: [192.168.33.12]
TASK: [ruby | rehash] *********************************************************
changed: [192.168.33.12]
TASK: [ruby | install bundler] ************************************************
changed: [192.168.33.12]
NOTIFIED: [nginx | restart nginx] *********************************************
changed: [192.168.33.12]
PLAY RECAP ********************************************************************
192.168.33.12 : ok=20 changed=19 unreachable=0 failed=0
Rebuilding the dev VM
Each time the dev VM is recreated, it gets a new SSH host key, so remove the old one from your local known_hosts before running Ansible or Capistrano again. Otherwise SSH sees a different key for the same IP address and refuses to connect. ssh-keygen -R deletes every entry for the given host from ~/.ssh/known_hosts:
ssh-keygen -R 192.168.33.12
Applying the same playbook to EC2
Once the dev VM works, the same playbook builds production:
ansible-playbook -i hosts rails.yml --limit prod
Both servers are ready. Part 2 deploys a Rails app to them with Capistrano.
Appendix: the rest of the code
---
- name: restart iptables
service: name=iptables state=restarted
---
- name: Set up iptables rules
copy: src=iptables-save dest=/etc/sysconfig/iptables
notify: restart iptables
- name: Change localtime to JST
copy: src=/usr/share/zoneinfo/Japan dest=/etc/localtime
- name: Add the EPEL software repository
yum: name=http://ftp.riken.jp/Linux/fedora/epel/6/i386/epel-release-6-8.noarch.rpm state=present
- name: Install build depends
yum: name={{ item }} state=latest
with_items:
- gcc
- gcc-c++
- git
- make
- tar
- vim
- name: Create /var/www directory
file: path=/var/www state=directory owner={{ login_user }} group={{ login_user }}
# copied from https://www.digitalocean.com/community/tutorials/how-to-deploy-rails-apps-using-unicorn-and-nginx-on-centos-6-5
upstream app {
server unix:/tmp/unicorn.my_app.sock fail_timeout=0;
}
server {
listen 80;
server_name localhost;
root /var/www/my_app/current/public;
try_files $uri/index.html $uri @app;
location @app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://app;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
---
- name: install build depends
yum: name={{ item }} state=latest
with_items:
- openssl-devel
- readline-devel
- zlib-devel
- mysql-devel # for the mysql2 gem
- name: clone rbenv repo
sudo: no
git: repo=https://github.com/sstephenson/rbenv.git dest={{ rbenv_root }}
- name: add rbenv initialization to profile
copy: src=rbenv.sh dest=/etc/profile.d/rbenv.sh owner=root group=root mode=0755
- name: check ruby-build installed
command: test -x /usr/local/bin/ruby-build
register: rbuild_present
ignore_errors: yes
- name: clone ruby-build repo
sudo: no
git: repo=https://github.com/sstephenson/ruby-build.git dest={{ rbenv_root }}/plugins/ruby-build
when: rbuild_present|failed
- name: install ruby-build
command: ./install.sh chdir={{ rbenv_root }}/plugins/ruby-build
when: rbuild_present|failed
- name: check ruby installed
sudo: no
shell: rbenv versions | grep {{ ruby_version }}
register: ruby_installed
ignore_errors: yes
- name: install ruby
sudo: no
shell: rbenv install {{ ruby_version }}
when: ruby_installed|failed
- name: set global ruby
sudo: no
shell: rbenv global {{ ruby_version }}
when: ruby_installed|failed
- name: rehash
sudo: no
shell: rbenv rehash
when: ruby_installed|failed
- name: install bundler
command: gem install bundler creates={{ rbenv_root }}/versions/{{ ruby_version }}/bin/bundle
sudo: no