Skip to Content

Deploying a Rails App to AWS Using Ansible

A quick overview and sample codes on how I used Ansible to deploy a Rails application to AWS.

Posted on 2 mins read

[Update 13 September 2016 - Merged playbooks into 1]

In the past week, I’ve been exploring how to automate the deployment of a Rails application into production on an AWS infrastructure. Ideally, I would like to have an environment consisting of 2 EC2 instances behind a load balancer and a Postgres database running on RDS. The Rails application requires Ruby 2.3.0 and uses PostgreSQL as a database.

This post assumes the Ansible host has been set up with AWS Access Key ID and AWS Secret Access Key as environment variables and there is an existing EC2 keypair.

The playbook deploy.yml does all the weight lifting from setting up AWS EC2 instances, PostgreSQL on AWS RDS, AWS ELB classic load balancer, installing ruby, rails and booting servers, up to registering EC2 instances to ELB.

Here is an overview of the roles, which can be found in the Gist below: 1. setup_aws 2. package_app 3. install_ruby 4. install_nginx 5. webserver 6. setup_elb

setup_aws does the following: - Creates a security group for EC2 which allows HTTP, HTTPS, and SSH access - Creates a security group for RDS which allows Postgres access on port 5432 - Starts 2 EC2 instances - Creates an EC2 ELB with a listener on port 80 - Starts a PostgreSQL instance on RDS

The other roles perform the following:
1. Installs Ruby, Rails, Nginx, and other dependencies on EC2 instances using roles install_ruby, install_nginx, 2. Precompiles and packages the Rails application locally using role package_app 3. Copies Rails application to the EC2 instances and boot in production mode using role webserver 4. Register both EC2 instances to ELB using role setup_elb